将List<T>存入Redis的工具类。

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

RedisUtils工具类

将List存入Redis的工具类。


一、代码

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Classname: RedisUtils
 * @Date: 2023-09-15
 * @Author: houshun
 */
public class RedisUtils {
    private RedisTemplate<String, String> redisTemplate;

    public RedisUtils(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private <T> byte[] serialize(T object) {
        String json = JSON.toJSONString(object, SerializerFeature.WriteClassName);
        return json.getBytes();
    }

    private <T> T deserialize(byte[] bytes, Class<T> clazz) {
        String json = new String(bytes);
        return JSON.parseObject(json, clazz);
    }

    public <T> void saveListInRedis(List<T> data, String key) {
        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
        connection.flushDb();

        for (int i = 0; i < data.size(); i++) {
            T item = data.get(i);
            byte[] serializedValue = serialize(item);
            byte[] serializedIndex = Integer.toString(i).getBytes();
            connection.hSet(key.getBytes(), serializedIndex, serializedValue);
        }
    }

    public <T> List<T> getListFromRedis(String key, Class<T> clazz) {
        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
        Map<byte[], byte[]> hashDataBytes = connection.hGetAll(key.getBytes());

        List<T> data = new ArrayList<>();
        for (Map.Entry<byte[], byte[]> entry : hashDataBytes.entrySet()) {
            T item = deserialize(entry.getValue(), clazz);
            data.add(item);
        }

        return data;
    }
}

2.使用方式

在springboot的application.yml配置文件中配置好Redisd的相关参数:
    redis:
      host: 192.168.2.227 #redis地址
      password:
      database: 0
      port: 30019
      timeout: 100000
调用
       @Autowired
    RedisTemplate redisTemplate; //注入redisTemplate
    RedisUtils redisUtils = new RedisUtils(redisTemplate);
        List<ResponseAccidentPointVo> list = redisUtils.getListFromRedis("accident_point_data", ResponseAccidentPointVo.class);
        // 如果 Redis 中没有数据,则从数据库中查询
        if (list == null || list.isEmpty()) {
            list = accidentpointMapper.getAllAccidentPointData();
            // 将查询结果存入 Redis
            redisUtils.saveListInRedis(list, "accident_point_data");
        }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值