JedisCluster和springboot整合
阿新 • • 發佈:2018-04-19
ng- cati ppc pri @value trim sta array framework
maven依賴
springboot整合jedisCluster相當簡單,maven依賴如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency>
加了這一個依賴之後就不要再加上jedis的這一個依賴了:
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
加這個可能在本身測試的時候,可能會導致jedisCluster對象正常,但是在測試的時候會發現set數據的時候會出現問題,我把jedis的依賴去掉之後,這個問題解決,因此不要加上jedis的這一個依賴,spring-boot-starter-redis這一個引入相關jedis需要的包。
application.properties配置
這裏的配置相當簡單,只需要天上redis的相關地址就行了,如下:
#redis cluster
spring.redis.cache.clusterNodes=192.168.xx.xx:6379,192.168.xx.:6380,192.168.xx.xx:6381
spring.redis.cache.commandTimeout=5000
相當簡單只需要幾個redis的地址和端口的字符串就可以了。
redisProperties
在這裏取springboot中的配置辦法相當多,可以使用如下方法:
@Inject private Environment environment; String properties = environment.getproperties("xxx")
或者是在加上註解,@Value(“”)會在配置文件中取相關名字的配置。
但在本文中決定使用另外一種方法,定義一個類命名問RedisProperties,在裏面定義的字段與配置文件中相對應,即可取到配置,如下:
@Component @ConfigurationProperties(prefix = "spring.redis.cache") @Data public class RedisProperties { private String clusterNodes; private Integer commandTimeout; }
如上,在使用時就能正常取到相關配置。
JedisClusterConfig
/** * 獲取JedisCluster的配置 */ @Configuration @ConditionalOnClass({JedisCluster.class}) @EnableConfigurationProperties(RedisProperties.class) public class JedisClusterConfig { @Inject private RedisProperties redisProperties; @Bean @Singleton public JedisCluster getJedisCluster() { String[] serverArray = redisProperties.getClusterNodes().split(","); Set<HostAndPort> nodes = new HashSet<>(); for (String ipPort: serverArray) { String[] ipPortPair = ipPort.split(":"); nodes.add(new HostAndPort(ipPortPair[0].trim(),Integer.valueOf(ipPortPair[1].trim()))); } return new JedisCluster(nodes, redisProperties.getCommandTimeout()); }
如上,配置就完成,現在進行測試一次。
測試
@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = SpringBootWebApplication.class) @WebAppConfiguration public class TestJedisCluster { @Inject private JedisCluster jedisCluster; @Test public void testJedis() { jedisCluster.set("test_jedis_cluster", "38967"); Assert.assertEquals("38967", jedisCluster.get("test_jedis_cluster")); jedisCluster.del("test_jedis_cluster"); } }
JedisCluster和springboot整合