Redis

写一个自定义的配置类来使用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存储的问题,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值