写一个自定义的配置类来使用redis
package com.hh.config;
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.RedisSerializer;
@Configuration
public class RedisConfig {
@Bean //RedisConnectionFactory factory使得这个方法可以连接数据库
public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
RedisTemplate<String,Object> template=new RedisTemplate<>();//实例化Template
template.setConnectionFactory(factory);//template有了工厂以后,就有了访问数据库的能力
/*java类的东西要存入数据库,就要设定一种方式转换(就是序列化?)*/
//设置key的序列化方式 RedisSerializer这个类有多种方法
template.setKeySerializer(RedisSerializer.string());//RedisSerializer.string()返回一个能序列化字符串的序列化器
//设置value的序列化方式
template.setValueSerializer(RedisSerializer.json());//数据多种多样,就用json接收吧
//设置hash 的key
template.setHashKeySerializer(RedisSerializer.string());
//设置 hash value的序列化方式
template.setHashValueSerializer(RedisSerializer.json());
template.afterPropertiesSet();//设置完后通过这个触发生效
return template;
}
}
调用方法查询数据库
@Autowired
private RedisTemplate<String,Object> redisTemplate;
//查询所有
@GetMapping("/findAll")
public String findEmp(Model model){
Object allEmps = redisTemplate.opsForList().range("list",0,-1);//去获取key为 allEmps 的值
List<Emp> empList=(List<Emp>)allEmps;//把数据转给List集合
List<Emp> emps = empService.findAll();
//如果empList为空就代表redis缓存里没有,就去数据找,并缓存在redis中
if(empList!=emps){
redisTemplate.opsForList().leftPushAll("list",emps);
Object allEmps1 = redisTemplate.opsForList().range("list",0,-1);
empList=(List<Emp>)allEmps1;
System.out.println(empList);
}
System.out.println(empList==emps);
System.out.println(empList);
System.out.println(emps);
model.addAttribute("emps",empList);//对应下方页面里面的emps
return "/ems/emplist";//这里返回的页面才会应用到上面这个“emps”
}
redis 数据库中成功拿到数据,但是这里出现了重复往redis存储的问题,