springboot整合redis集群
1.创建springboot项目
在springboot项目中整合redis集群有三种方式(jedis,lettuce,RedisTemplate)下面依次讲解
一、springboot整合redis(jedis)
1.修改pom.xml配置文件
<!--jedis-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>4.3.1</version>
</dependency>
2.创建一个测试类
public class jedisDemo {
public static void main(String[] args) {
//connection 通过指定ip和端口号获取连接
Jedis jedis = new Jedis("192.168.10.129", 6382);
//指定访问服务器的密码
jedis.auth("123456");
//获得jedis客户端跟jdbc一样
System.out.println(jedis.ping());
//keys
Set<String> keys = jedis.keys("*");
System.out.println(keys);
//string
String set = jedis.set("k1", "v1");
System.out.println(jedis.get("k1"));
//list
jedis.lpush("list","11","22","33");
List<String> list = jedis.lrange("list", 0, -1);
for (String s : list) {
System.out.println(s);
}
// set
jedis.sadd("orders","jd001");
jedis.sadd("orders","jd002");
jedis.sadd("orders","jd003");
Set<String> orders = jedis.smembers("orders");
for (Iterator iterator = orders.iterator(); iterator.hasNext();){
String string = (String)iterator.next();
System.out.println(string);
}
jedis.srem("orders","jd002");
System.out.println(jedis.smembers("orders").size());
// hash
jedis.hset("hash1","userName","lisi");
System.out.println(jedis.hget("hash1", "userName"));
HashMap<String, String> map = new HashMap<>();
map.put("telphone","123456");
map.put("address","zhongshan");
map.put("email","1233456@qq.com");
jedis.hmset("hash2",map);
List<String> result = jedis.hmget("hash2", "telphone", "email");
for (String element : result) {
System.out.println(element);
}
// zset
jedis.zadd("zset01",60d,"v1");
jedis.zadd("zset01",70d,"v2");
jedis.zadd("zset01",80d,"v3");
jedis.zadd("zset01",90d,"v4");
List<String> zset01 = jedis.zrange("zset01", 0, -1);
zset01.forEach(System.out::println);
}
}
直接运行测试
二、springboot整合redis(lettuce)
1.修改pom.xml 文件
<!-- lettuce-->
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
<version>6.2.1.RELEASE</version>
</dependency>
2.创建测试类(lettuceDemo)
public class lettuceDemo {
public static void main(String[] args) {
//使用构建器链式编程来builder我们redisURI
RedisURI uri = RedisURI.builder().redis("192.168.10.129")
.withPort(6382)
.withAuthentication("default", "123456")
.build();
//创建连接客户端
RedisClient redisClient = RedisClient.create(uri);
StatefulRedisConnection<String, String> conn = redisClient.connect();
//通过conn创建操作的command
RedisCommands<String, String> commands = conn.sync();
//===========biz==============
// keys
List<String> keys = commands.keys("*");
System.out.println(keys);
// string
commands.set("k5","hello-lettuce");
System.out.println(commands.get("k5"));
// list
commands.lpush("myList2","v1","v2","v3");
List<String> myList2 = commands.lrange("myList2", 0, -1);
for (String s : myList2) {
System.out.println(s);
}
//set
commands.sadd("mySet2", "v1", "v2", "v3");
Set<String> mySet2 = commands.smembers("mySet2");
for (String s : mySet2) {
System.out.println(s);
}
//hash
HashMap<String, String> map = new HashMap<>();
map.put("telphone", "123456123");
map.put("address", "zhongshan");
map.put("email", "1233456@qq.com");
commands.hmset("myHash2", map);
Map<String, String> retMap = commands.hgetall("myHash2");
for (String k : retMap.keySet()) {
System.out.println("k=" + k + "===============" + "v=" + retMap.get(k));
}
// zset
commands.zadd("myZset2", 100.0, "s1", 200.0, "s2", 90.0, "s3");
List<String> myZset2 = commands.zrange("myZset2", 0, 10);
for (String s : myZset2) {
System.out.println(s);
}
//sort
SortArgs sortArgs = new SortArgs();
sortArgs.alpha();
sortArgs.desc();
List<String> myList3 = commands.sort("myList3", sortArgs);
for (String s : myList3) {
System.out.println(s);
}
//===========biz==============
//各种关闭释放资源
conn.close();
redisClient.shutdown();
}
}
直接测试
三、springboot整合redis(RedisTemplate)
1.修改pom.xml
<!--SpringBoot通用依赖模块-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- SpringBoot与Redis整合依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!--通用基础配置-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
2.修改application.properties配置文件
server.port=7777
spring.application.name=redisCluster
# ========================logging=====================
logging.level.root=info
logging.level.com.atguigu.redis7=info
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger- %msg%n
#产生日志的路径
logging.file.name=H:/redisCluster.log
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger- %msg%n
# ========================swagger=====================
spring.swagger2.enabled=true
##在springboot2.6.X结合swagger2.9.X会提示documentationPluginsBootstrapper空指针异常,
##原因是在springboot2.6.X中将SpringMVC默认路径匹配策略从AntPathMatcher更改为PathPatternParser,
## 导致出错,解决办法是matching-strategy切换回之前ant_path_matcher
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
# ========================redis集群=====================
spring.redis.password=123456
# 获取失败 最大重定向次数
spring.redis.cluster.max-redirects=3
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=-1ms
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
#支持集群拓扑动态感应刷新,自适应拓扑刷新是否使用所有可用的更新,默认false关闭
spring.redis.lettuce.cluster.refresh.adaptive=true
#定时刷新
spring.redis.lettuce.cluster.refresh.period=2000
spring.redis.cluster.nodes=192.168.10.128:6381,192.168.10.129:6382,192.168.10.130:6383,192.168.10.1:6384,192.168.10.2:6385,192.168.10.20:6386
3.创建业务类
4.编辑OrderService业务类
@Service
@Slf4j
public class OrderService {
public static final String ORDER_KEY = "ord:";
@Resource
private RedisTemplate redisTemplate;
public void addOrder() {
int keyId = ThreadLocalRandom.current().nextInt(1000) + 1;
String serialNo = UUID.randomUUID().toString();
String key = ORDER_KEY + keyId;
String value = "美团订单" + serialNo;
redisTemplate.opsForValue().set(key,value);
log.info("key:{}",key);
log.info("value:{}",value);
}
public String getOrderById(Integer keyId){
return String.valueOf(redisTemplate.opsForValue().get(ORDER_KEY + keyId));
}
}
5.编辑OrderController控制类
@RestController
@Slf4j
@Api(tags = "订单接口")
public class OrderController {
@Resource
private OrderService orderService;
@ApiOperation("新增订单接口")
@RequestMapping(value = "/order/add", method = RequestMethod.POST)
public void addOrder() {
orderService.addOrder();
}
@ApiOperation("根据keyId查询订单")
@RequestMapping(value = "/order/{keyId}", method = RequestMethod.GET)
public String getOrderById(@PathVariable Integer keyId) {
return orderService.getOrderById(keyId);
}
}
6.修改Swagger配置类
@Configuration
@EnableSwagger2
public class SwaggerConfig
{
@Value("${spring.swagger2.enabled}")
private Boolean enabled;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(enabled)
.select()
.apis(RequestHandlerSelectors.basePackage("com.yang.rediscluster")) //你自己的package
.paths(PathSelectors.any())
.build();
}
public ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot利用swagger2构建api接口文档 "+"\t"+ DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDateTime.now()))
.description("springboot+redis整合")
.version("1.0")
.build();
}
}
7.在主启动类上加上@EnableSwagger2注解
8.访问swagger调试界面
9.使用swagger调试刚刚我们写的接口
10.在redis服务器上查看刚刚写入的数据
发现写是写成功了但是出现了乱码的问题(因为springboot默认的序列化会出现乱码,我们要的key要使用string的方式序列化,value要使用json的方式序列化)
11.在RedisConfig配置类上面配置
@Configuration
public class RedisConfig
{
/**
* redis序列化的工具配置类,下面这个请一定开启配置
* 127.0.0.1:6379> keys *
* 1) "ord:102" 序列化过
* 2) "\xac\xed\x00\x05t\x00\aord:102" 野生,没有序列化过
* this.redisTemplate.opsForValue(); //提供了操作string类型的所有方法
* this.redisTemplate.opsForList(); // 提供了操作list类型的所有方法
* this.redisTemplate.opsForSet(); //提供了操作set的所有方法
* this.redisTemplate.opsForHash(); //提供了操作hash表的所有方法
* this.redisTemplate.opsForZSet(); //提供了操作zset的所有方法
* @param lettuceConnectionFactory
* @return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory)
{
RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(lettuceConnectionFactory);
//设置key序列化方式string
redisTemplate.setKeySerializer(new StringRedisSerializer());
//设置value的序列化方式json,使用GenericJackson2JsonRedisSerializer替换默认序列化
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
12.再次启动主动类且在插入数据
发现key已经完成序列化