redis热点数据储存,加快访问数据库中的数据

2024-04-14  本文已影响0人  祝家庄打烊

实体类序列化,便于redis储存(UserEntity)

实体类序列化

在service层进行redis存储(UserService)

package com.example.demo.service;

import com.example.demo.entity.UserEntity;
import com.example.demo.mapper.UserMapper;
import com.example.demo.mapper.UserMapperZs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.data.redis.core.RedisTemplate;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserMapperZs userMapperZs;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    public UserEntity findById(int id){
        return userMapper.findById(id);
    }
    public Object findByIdZs(int id){
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);
        Object userList = redisTemplate.opsForValue().get("userList");
        System.out.println("userList");
        System.out.println(userList);
        if(null == userList){
            synchronized (this){
                if(null == userList){
                    System.out.println("从mysql中查询数据中。。。。。。");
                    // 从数据库中查询数据
                    userList = userMapperZs.findById(id);
                    System.err.println(userList);
                    System.out.println("返回數據1");
                    // 放入redis
                    redisTemplate.opsForValue().set("userList",userList);
                    System.out.println("返回數據2");
                }
            }
        }else{
            System.out.println("从redis中查询数据中。。。。。。");
        }
        System.out.println("返回數據3");
        return userList;
    }
}

注意当前表有更改,记住删除redis缓存中的该字段

上一篇 下一篇

猜你喜欢

热点阅读