springboot整合redis作爲緩存
1.引入jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.配置地址
在application.yum文件中配置redis的地址:
spring:
redis:
host: ip地址
端口不需要填寫,默認6379,密碼沒有設置不需填寫。
3.操作redis
在springboot中對redis進行操作需要注入操作類
@Autowired
RedisTemplate redisTemplate;
//對字符串進行操作
@Autowired
StringRedisTemplate stringRedisTemplate;
簡單操作:
(1)存取KV值
stringRedisTemplate.opsForValue().append("k1","v1");
String msg = stringRedisTemplate.opsForValue().get("k1");
System.out.println("獲取值:" + msg);
(2)存入對象
首先添加配置類MyRedisConfig類,寫入序列化方法。
@Configuration
public class MyRedisConfig {
@Bean
public RedisTemplate<Object, Object> myRedisTemplate(RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Object> jk2 = new Jackson2JsonRedisSerializer<Object>(Object.class);
template.setDefaultSerializer(jk2);
return template;
}
}
實體類實現接口Serializable
public class Teacher implements Serializable {
private static final long serialVersionUID = 980262116381279952L;
private int id;
private String tname;
.
.
.
.
測試
@Autowired
RedisTemplate<Object, Object> myRedisTemplate;
@Test
public void redisTest(){
//查詢數據
Teacher teacher = teacherMapper.queryById(1);
myRedisTemplate.opsForValue().set("teacher",teacher);
}