1.jedis连接redis存取List<String>去掉重复value:
获取:
smembers获取Set<String>
list的addAll即可把set转换为list
存:
sadd
private List<Station> getStationIds() {
List<Station> stations = new ArrayList<>();
try {
String key = GlobalConstant.STATION;
// 从Redis缓存中获取List<Station>数据
Set<String> set = redisClientTemplate.smembers(key);
List<String> storedList = new ArrayList<>();
storedList.addAll(set);
if (CollectionUtils.isEmpty(storedList)) {
stations = stationService.getStationsList();
if (stations == null || stations.isEmpty()) {
return null;
}
// 将List<Station>数据存入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<Station>去掉重复value:
获取:
smembers获取Set<String>
list的addAll即可把set转换为list
存:
sadd
与上面不同的是,存储的时候,存的是一个一个json,取得也是json。存取json注意方式方法一样,比如我现在存得json使用得是jackson得writeValueAsString方法,取得话用jackson得readValue方法。
private List<Device> getByStationId(String stationId) {
List<Device> deviceInfoList = new ArrayList<>();
try {
String key = GlobalConstant.DEVICE+stationId;
// 从Redis缓存中获取List<Device>数据
Set<String> set = redisClientTemplate.smembers(key);
List<String> storedList = new ArrayList<>();
storedList.addAll(set);
if (CollectionUtils.isEmpty(storedList)) {
// 获取设备信息
List<Device> device_infos = deviceInfoService.getDevicesByStationId(stationId);
if (device_infos == null || device_infos.isEmpty()) {
return null;
}
// 将List<Device>数据存入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;
}