Guice使用入门以及整合Redis
guice是什么?(借用百度百科的说明和对比)
Guice是Google开发的一个轻量级,基于Java5(主要运用泛型与注释特性)的依赖注入框架(IOC)。Guice非常小而且快。Guice是类型安全的,它能够对构造函数,属性,方法(包含任意个参数的任意方法,而不仅仅是setter方法)进行注入。Guice采用Java加注解的方式进行托管对象的配置,充分利用IDE编译器的类型安全检查功能和自动重构功能,使得配置的更改也是类型安全的。Guice提供模块对应的抽象module,使得架构和设计的模块概念产物与代码中的module类一一对应,更加便利的组织和梳理模块依赖关系,利于整体应用内部的依赖关系维护,而其他IOC框架是没有对应物的。此外,借助privateModule的功能,可以实现模块接口的明确导出和实现封装,使得支持多数据源这类需求实现起来异常简单。
我个人的见解:对于小型独立项目,比如:定时任务,后台辅助进程等等,这类项目完全可以用guice实现,简洁易懂、代码量少、jar包又小简直完美啊!ps:目前我已经改造了几个小工程了;
我的工程目录如下:
首先添加相关依赖,打开pom.xml
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>4.2.0</version>
</dependency>
配置文件属性值
redis.database=0
redis.host=10.0.2.13
redis.port=6379
redis.password=
#连接池最大连接数(使用负值表示没有限制)
redis.pool.max.active=10000
# 连接池中的最大空闲连接
redis.pool.max.idle=100
#连接池最大阻塞等待时间(使用负值表示没有限制)
redis.pool.max.wait=-1
# 连接池中的最小空闲连接
redis.pool.min.idle=0
# 连接超时时间(毫秒)
redis.timeout=0
新建一个redis相关的provider,用于redis配置
package com.example.provider;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.name.Named;
import com.yingda.xsignal2.util.redis.RedisExtendClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedisPool;
import java.util.Arrays;
import java.util.Objects;
/**
* @author xiaofeng
* @version V1.0
* @title: RedisClientProvider
* @package: com.example.provider
* @description: TODO
* @date 2018/6/25 17:23
*/
public class RedisClientProvider implements Provider<RedisExtendClient> {
Logger logger = LoggerFactory.getLogger(getClass());
@Inject
@Named("redis.database")
private Integer database;
@Inject
@Named("redis.host")
private String host;
@Inject
@Named("redis.port")
private Integer port;
@Inject
@Named("redis.password")
private String password;
@Inject
@Named("redis.pool.max.active")
private Integer maxActive;
@Inject
@Named("redis.pool.max.idle")
private Integer maxIdle;
@Inject
@Named("redis.pool.max.wait")
private Integer maxWait;
@Inject
@Named("redis.pool.min.idle")
private Integer minIdle;
@Inject
@Named("redis.timeout")
private Integer timeout;
private static ShardedJedisPool shardedPool;
private ShardedJedisPool getJedisPool() {
if (Objects.isNull(shardedPool)) {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(this.maxActive);
config.setMaxWaitMillis(this.maxWait);
config.setMaxIdle(this.maxIdle);
config.setMinIdle(this.minIdle);
JedisShardInfo info = new JedisShardInfo(this.host, this.port.intValue(),
this.timeout.intValue());
if (this.password != null && !this.password.isEmpty()) {
info.setPassword(password);
}
shardedPool = new ShardedJedisPool(config, Arrays.asList(new JedisShardInfo[]{info}));
} else {
logger.error("initialze operate error,please waitting.....");
return shardedPool;
}
return shardedPool;
}
@Override
public RedisExtendClient get() {
return new RedisExtendClient(getJedisPool());
}
}
新建一个module,用于绑定相关依赖关系
package com.example.module;
import com.example.provider.RedisClientProvider;
import com.example.utils.PropertyUtil;
import com.google.inject.AbstractModule;
import com.google.inject.Scopes;
import com.google.inject.name.Names;
import com.yingda.xsignal2.util.redis.RedisExtendClient;
/**
* @author xiaofeng
* @version V1.0
* @title: RollbackModule
* @package: com.example.module
* @description: TODO
* @date 2018/6/25 17:40
*/
public class RollbackModule extends AbstractModule {
private String file = "config/app.properties";
@Override
protected void configure() {
//绑定配置属性
Names.bindProperties(binder(), PropertyUtil.loadFile(file, getClass()));
// bind(Config.class).toProvider(ConfigProvider.class);
//绑定redis
bind(RedisExtendClient.class).toProvider(RedisClientProvider.class).in(Scopes.SINGLETON);
}
}
用于读取配置文件的util工具
package com.example.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* @author xiaofeng
* @version V1.0
* @title: PropertyUtil
* @package: com.example.utils
* @description: 加载配置文件
* @date 2018/6/25 17:15
*/
public class PropertyUtil {
/**
* 读取配置文件属性
*
* @param prefix
* @param cla
* @return
*/
public static Properties loadFile(String prefix, Class<?> cla) {
String fileName = prefix;
Properties prop = new Properties();
InputStream in = null;
try {
in = cla.getResource("/" + fileName).openStream();
prop.load(in);
} catch (IOException e) {
e.printStackTrace();
}
return prop;
}
}
主函数入口类
package com.example;
import com.example.module.RollbackModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.yingda.xsignal2.util.redis.RedisExtendClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author xiaofeng
* @version V1.0
* @title: MyApplication
* @package: com.example
* @description: TODO
* @date 2018/6/25 17:40
*/
public class MyApplication {
private Logger logger = LoggerFactory.getLogger(getClass());
private Injector injector;
private RedisExtendClient redisExtendClient;
private MyApplication() {
logger.info("init something......");
injector = Guice.createInjector(new RollbackModule());
redisExtendClient = injector.getInstance(RedisExtendClient.class);
}
private void run() {
logger.info("to do something......");
redisExtendClient.set("test_guice","test_guice");
}
public static void main(String[] args) {
MyApplication app = new MyApplication();
try {
app.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}
最后启动程序,通过redis客户端工具查看是否已生成相关key
至此,我们的第一个guice项目已经完成!