整合redis作为缓存
导入依赖:
配置注解:
操作数据
Redis 常见的五大数据类型
String (字符串)、List(列表)、Set(集合)、hash(散列)、zset(有序集合)
@Test
public void test01(){
//给redis保存数据
stringRedisTemplate.opsForValue().append("msg","hello");
//读取数据
String msg = stringRedisTemplate.opsForValue().get("msg");
//存入数据
stringRedisTemplate.opsForList().leftPush("mylist","1");
stringRedisTemplate.opsForList().leftPush("mylist","2");
stringRedisTemplate.opsForList().leftPush("mylist","3");
//取出数据
String leftPop = stringRedisTemplate.opsForList().leftPop("mylist");
stringRedisTemplate.opsForSet().add("myset","a");
stringRedisTemplate.opsForSet().add("myset","b");
stringRedisTemplate.opsForSet().pop("myset");
stringRedisTemplate.opsForHash().hasKey("aa","bb");
}
当我们进行如下代码测试的时候
我们想保存我们查询出来的employee数据,首先报错误 说com.atshiyou.entity.employee无法序列化
所以我们就将这个class 实现序列化:
”
查看redis发现数据存储格式是这样的:
这不是人类能读懂的,我们想将这些数据转化成Json数据格式的数据,怎么办呢?
修改源码:因为redis是默认使用jdk的序列化格式对数据进行处理的
我们就只需要重写该方法
上面代码展示的就是 redis使用Jdk序列方法
我们就需要重写如下的代码,文件找不到就直接 搜索文件名
我们重新创建一个conf文件夹,然后在文件夹下创建一个java文件,将上面的方法重写,并添加新的序列化
package com.atshiyou.cache.conf;
import com.atshiyou.cache.bean.Employee;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
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.Jackson2JsonRedisSerializer;
import java.net.UnknownHostException;
@Configuration
public class MyredisConfig {
@Bean
public RedisTemplate<Object, Employee> EmployeeredisTemplate(
RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
RedisTemplate<Object, Employee> template = new RedisTemplate<Object, Employee>();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
template.setDefaultSerializer(ser);
return template;
}
}
在主文件中 注入该方法:
@Autowired
RedisTemplate<Object, Employee> EmployeeredisTemplate;
使用新的redistemplate
@Test
public void test02(){
Employee employee = employeeMapper.getEmpById(1);
// redisTemplate.opsForValue().set("emp-01",employee);
EmployeeredisTemplate.opsForValue().set("emp-01",employee);
}