Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API
1、添加Maven依赖 (或jar包)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
2、配置数据源相关信息
#redis cluster
spring.redis.cache.clusterNodes=192.168.10.20:6000,192.168.10.20:6001,192.168.10.20:6002,192.168.10.20:6003,192.168.10.20:6004,192.168.10.20:6005
spring.redis.cache.commandTimeout=5000
3、配置Redis
package com.cl.config;
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
@Configuration
@ConditionalOnClass({ JedisCluster.class })
public class JedisClusterConfig {
@Value("${spring.redis.cache.clusterNodes}")
private String clusterNodes;
@Value("${spring.redis.cache.commandTimeout}")
private Integer commandTimeout;
@Bean
public JedisCluster getJedisCluster() {
String[] serverArray = clusterNodes.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, commandTimeout);
}
}
4、测试
Maven 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
Junit
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import com.cl.config.Application;
import redis.clients.jedis.JedisCluster;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class) // 指定spring-boot的启动类
@WebAppConfiguration
public class TestJedis {
private Logger logger = Logger.getLogger(getClass());
@Autowired
private JedisCluster jedisCluster;
@Test
public void testJedis() {
jedisCluster.set("test_jedis_cluster", "38967");
String string = jedisCluster.get("test_jedis_cluster");
logger.info(string);
jedisCluster.del("test_jedis_cluster");
}
}