jedis连接redis存取List<String>和List<Station>

1.jedis连接redis存取List去掉重复value:

获取:

smembers获取Set

list的addAll即可把set转换为list

存:

sadd

private List getStationIds() {
    List stations = new ArrayList<>();
    try {
        String key = GlobalConstant.STATION;
        // 从Redis缓存中获取List数据
        Set set = redisClientTemplate.smembers(key);
        List storedList = new ArrayList<>();
        storedList.addAll(set);
        if (CollectionUtils.isEmpty(storedList)) {
            stations = stationService.getStationsList();
            if (stations == null || stations.isEmpty()) {
                return null;
            }
            // 将List数据存入Redis缓存中
            for (Station station : stations) {
                redisClientTemplate.sadd(key, station.getStationId());
            }
        }else{
            // 从缓存中获取 转换成原始的Station对象
            for (String st : storedList) {
                stations.add(new Station(st));
            }
        }

    } catch (Exception exception) {
        loggerA.error("缓存station的信息到redis异常:{}", exception.getMessage());
    }
    return stations;
}

2.jedis连接redis存取List去掉重复value:

获取:

smembers获取Set

list的addAll即可把set转换为list

存:

sadd

与上面不同的是,存储的时候,存的是一个一个json,取得也是json。存取json注意方式方法一样,比如我现在存得json使用得是jackson得writeValueAsString方法,取得话用jackson得readValue方法。

private List getByStationId(String stationId) {
        List deviceInfoList = new ArrayList<>();
        try {
            String key = GlobalConstant.DEVICE+stationId;
            // 从Redis缓存中获取List数据
            Set set = redisClientTemplate.smembers(key);
            List storedList = new ArrayList<>();
            storedList.addAll(set);
            if (CollectionUtils.isEmpty(storedList)) {
                // 获取设备信息
                List device_infos = deviceInfoService.getDevicesByStationId(stationId);
                if (device_infos == null || device_infos.isEmpty()) {
                    
                    return null;
                }
                // 将List数据存入Redis缓存中
                for (Device deviceInfo : device_infos) {
                    redisClientTemplate.sadd(key, deviceInfo.toJSON());
                }
            }else{
                // 从缓存中获取 转换成原始的Device对象
                for (String st : storedList) {
                    deviceInfoList.add(ObjectMapperUtils.fromJSON(st, Device.class));
                }
            }
        } catch (Exception exception) {
            loggerA.error("缓存Device的信息到redis异常:{}", exception.getMessage());
        }
        return deviceInfoList;
    }

你可能感兴趣的:(redis,数据库,缓存)