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);
}