1 、在pom.xml 添加Spring Boot 的redis 依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、@Bean方法重写RedisTemplate 进行序列化
package com.example.redis;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
@SuppressWarnings("all")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(factory);
// 设置value的序列化规则和 key的序列化规则
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
System.out.println(redisTemplate);
return redisTemplate;
}
}
3、进行redis的操作
package com.example.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserControler {
@Autowired
RedisTemplate redisTemplate; // 注入RedisTemplate
@RequestMapping("/setUser")
public boolean setUser(){
try {
redisTemplate.opsForValue().set("22", "3333"); //设置value值
System.out.println("44444");
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@RequestMapping("/getUser")
public boolean getUser(){
try {
String value=(String)redisTemplate.opsForValue().get("22");// 通过key值获取value
System.out.println(value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
properties 文件配置
# redis地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
Spring boot 默认使用lettuce 连接池,默认没有开启连接池。
需要在properties配置文件下配置连接池信息
# Lettuce
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.lettuce.pool.max-wait=10000
# 连接池中的最大空闲连接
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.lettuce.pool.min-idle=0
# 关闭超时时间
spring.redis.lettuce.shutdown-timeout=100