以下是修改后的代码:
import org.apache.ibatis.session.SqlSession;
import org.springframework.data.redis.core.RedisTemplate;
import com.alibaba.fastjson.JSON;
import java.util.List;
import java.util.stream.Collectors;
import java.util.logging.Logger;
public class OfferingCacheWithMyBatisAndRedisTemplate {
private static final Logger logger = Logger.getLogger(OfferingCacheWithMyBatisAndRedisTemplate.class.getName());
private static final String REDIS_KEY = "Cache_key";
public static void main(String[] args) {
try (SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession()) {
// 使用 MyBatis 查询数据库数据并获取列表
List<OfferingEntity> offeringList = sqlSession.selectList("mapper.OfferingMapper.selectOfferings");
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
// 假设你已经正确配置了连接工厂
redisTemplate.setConnectionFactory(redisConnectionFactory);
offeringList.stream()
.forEach(offering -> {
String name = offering.getName();
boolean hasField = redisTemplate.opsForHash().hasKey(REDIS_KEY, name);
String cachedValue = hasField? (String) redisTemplate.opsForHash().get(REDIS_KEY, name) : null;
String jsonEntity = JSON.toJSONString(offering);
if (!hasField || (cachedValue!= null &&!cachedValue.equals(jsonEntity))) {
// 如果数据不同或者未缓存,更新缓存并记录日志
redisTemplate.opsForHash().put(REDIS_KEY, name, jsonEntity);
logger.info("Updated cache. Name: " + name);
}
});
sqlSession.commit();
} catch (Exception e) {
logger.severe("Error in cache update: " + e.getMessage());
}
}
// 假设的数据库实体类
static class OfferingEntity {
private String name;
private String code;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
}
在这段代码中,将实体类转换为 JSON 格式字符串进行存储。当需要获取数据时,可以从缓存中取出 JSON 字符串,再转换回实体类对象进行使用。这样可以方便地存储和组装数据。