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;}@Overridepublic 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";@Overrideprotected void configure() {//綁定配置屬性Names.bindProperties(binder(), PropertyUtil.loadFile(file, getClass())); // bind(Config.class).toProvider(ConfigProvider.class);//綁定redisbind(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項目已經完成!
總結
以上是生活随笔為你收集整理的Guice使用入门以及整合Redis的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CentOS7挂载磁盘,4T磁盘挂载方法
- 下一篇: linux cmake编译源码,linu