springboot之整合jedis的使用
阿新 • • 發佈:2018-12-28
在pom.xml匯入jedis包
<!--redis客戶端--> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
單機版
在resources下建立redis.properties檔案,裡面配置自己的redis的ip和埠號 ,如果自己想設定其它的屬性的話也可以自己加幾個
然後往ioc容器中加入JedisPool物件,因為使用了springboot了,就最好不用使用spring配置檔案了,所以就使用java類註解方式建立這個物件
package com.buba.configuration; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringBootConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.PropertySource; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; @SpringBootConfiguration @PropertySource(value = {"classpath:redis/redis.properties"}) public class RedisConfiguration { @Value("${redis.node.maxTotal}") private Integer maxTotal; @Value("${redis.node.host}") private String host; @Value("${redis.node.port}") private Integer port; public JedisPoolConfig jedisPoolConfig(){ //這個是修改redis效能的時候需要的物件 JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxTotal(maxTotal); return jedisPoolConfig; } @Bean //這個註解注入工廠的名稱是方法名 public JedisPool jedisPool(){ JedisPoolConfig jedisPoolConfig = jedisPoolConfig(); return new JedisPool(jedisPoolConfig,host,port); } }
然後進行測試
叢集版
同樣先導包,相同的包
然後寫配置檔案
然後寫配置類,沒啥邏輯就是把字串按照那格式分割開
package com.buba.configuration; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringBootConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.PropertySource; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.JedisCluster; import java.util.HashSet; import java.util.Set; @SpringBootConfiguration @PropertySource(value = {"classpath:redis/redisCluster.properties"}) public class RedisClusterConfiguration { @Value("${redis.cluster.nodes}") private String nodes; @Bean public JedisCluster jedisCluster(){ Set<HostAndPort> set = new HashSet<>(); HostAndPort hp = null; String[] nodeStr = nodes.split(","); if(nodeStr!=null&&nodeStr.length>0){ for(int i=0;i<nodeStr.length;i++){ String[] hostPort = nodeStr[i].split(":"); if(hostPort!=null&&hostPort.length>0){ hp = new HostAndPort(hostPort[0],Integer.valueOf(hostPort[1])); set.add(hp); } } } JedisCluster jedisCluster = new JedisCluster(set); return jedisCluster; } }