1.Maven引入jar包
<!-- redis缓存引入-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--letture pool 缓存连接池-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
2.application配置文件
spring:
profiles:
active: dev
redis:
database: 0
host: localhost
port: 6379
password:
lettuce:
pool:
max-active: 8
max-wait: 8
min-idle: 0
3.配置类配置RedisTemplate
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory connectionFactory){
RedisTemplate<String,Serializable> redisTemplate=new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setConnectionFactory(connectionFactory);
return redisTemplate;
}
}
4.根据不同数据类型写入
5.测试
@Test
public void demo() {
Admin admin=new Admin();
admin.setUsername("admin");
admin.setPassword("123");
ValueOperations valueOperations = redisTemplate.opsForValue();
//设置值
valueOperations.set("admin",admin);
System.out.println("------------------写入缓存成功------------------");
Admin admin1 = (Admin) valueOperations.get("admin");
System.out.println(admin1);
}