本次和大家分享的是在springboot整合使用redis,這裡使用的是redis的jedis用戶端(這裡我docker啟動並執行redis,可以參考 docker快速搭建幾個常用的第三方服務),如下添加依賴:
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId></dependency>
然後需要redis的相關配置(這裡我的redis密碼是空),在application.yml設定如:
spring: redis: single: 192.168.146.28:6378 jedis: pool: max-idle: 8 max-active: 8 max-wait: 3000 timeout: 3000 password:
這是redis的一般配置,具體調優可以設定這些參數,下面在JedisConfig類中讀取這些設定:
1 @Value("${spring.redis.single}") 2 private String strSingleNode; 3 4 @Value("${spring.redis.jedis.pool.max-idle}") 5 private Integer maxIdle; 6 7 @Value("${spring.redis.jedis.pool.max-active}") 8 private Integer maxActive; 9 10 @Value("${spring.redis.jedis.pool.max-wait}")11 private Integer maxAWait;12 13 @Value("${spring.redis.timeout}")14 private Integer timeout;15 16 @Value("${spring.redis.password}")17 private String password;
有上面的配置,就需要有代碼裡面設定下,這裡建立一個返回JedisPoolConfig的方法
1 /** 2 * jedis配置 3 * 4 * @return 5 */ 6 public JedisPoolConfig getJedisPoolConfig() { 7 JedisPoolConfig config = new JedisPoolConfig(); 8 config.setMaxIdle(maxIdle); #最大空閑數 9 config.setMaxWaitMillis(maxAWait); #最大等待時間10 config.setMaxTotal(maxActive); #最大串連數11 return config;12 }
有了配置,接下來就建立JedisPool,這裡把JedisPool託管到spring中
1 /** 2 * 擷取jedispool 3 * 4 * @return 5 */ 6 @Bean 7 public JedisPool getJedisPool() { 8 JedisPoolConfig config = getJedisPoolConfig(); 9 System.out.println("strSingleNode:" + this.strSingleNode);10 String[] nodeArr = this.strSingleNode.split(":");11 12 JedisPool jedisPool = null;13 if (this.password.isEmpty()) {14 jedisPool = new JedisPool(15 config,16 nodeArr[0],17 Integer.valueOf(nodeArr[1]),18 this.timeout);19 } else {20 jedisPool = new JedisPool(21 config,22 nodeArr[0],23 Integer.valueOf(nodeArr[1]),24 this.timeout,25 this.password);26 }27 return jedisPool;28 }
上面簡單區分了無密碼的情況,到此jedis的配置和串連池就基本搭建完了,下面就是封裝使用的方法,這裡以set和get為例;首先建立個JedisComponent組件,代碼如下:
/** * Created by Administrator on 2018/8/18. */@Componentpublic class JedisComponent { @Autowired JedisPool jedisPool; public boolean set(String key, String val) { Jedis jedis = null; try { jedis = jedisPool.getResource(); return jedis.set(key, val).equalsIgnoreCase("OK"); } finally { if (jedis != null) { jedis.close(); } } } public <T> boolean set(String key, T t) { String strJson = JacksonConvert.serilize(t); if (strJson.isEmpty()) { return false; } return this.set(key, strJson); } public String get(String key) { Jedis jedis = null; try { jedis = jedisPool.getResource(); return jedis.get(key); } finally { if (jedis != null) { jedis.close(); } } } public <T> T get(String key, Class<T> tClass) { String strJson = this.get(key); return JacksonConvert.deserilize(strJson, tClass); }}
有了對jedis的調用封裝,我們在Controller層的測試案例如下:
1 @Autowired 2 JedisComponent jedis; 3 4 @GetMapping("/setJedis/{val}") 5 public boolean setJedis(@PathVariable String val) { 6 return jedis.set("token", val); 7 } 8 9 @GetMapping("/getJedis")10 public String getJedis() {11 return jedis.get("token");12 }
運行set和get的介面效果如: