- 注解: http://wx0725.top/index.php/archives/640/
- API http://wx0725.top/index.php/archives/647/
SpringBoot 在使用 API、注解 實作對比
1. 為什么保存的鍵值一個是字串,一個包含十六進制?


看到十六進制,肯定是因為API保存時使用的序列化和注解的是不同的
下面不是全部代碼,只是一個例子
- 1.1 注解代碼:
@Cacheable(cacheNames = "comment", key = "'comment-'+#p0", unless = "#result==null")
public CommentMain findById(int id) {
Optional<CommentMain> optionalCommentMain = commentRepository.findById(id);
System.out.println(optionalCommentMain);
if (optionalCommentMain.isPresent()) {
return optionalCommentMain.get();
}
return null;
}
- 1.2 API 代碼
public CommentMain findById(int id) {
Object o = redisTemplate.opsForValue().get("comment-" + id);
if (o != null) {
return (CommentMain) o;
} else {
Optional<CommentMain> optionalCommentMain = commentRepository.findById(id);
if (optionalCommentMain.isPresent()) {
CommentMain commentMain = optionalCommentMain.get();
redisTemplate.opsForValue().set("comment-" + id, commentMain, 1, TimeUnit.DAYS);
return commentMain;
} else {
return null;
}
}
}
1.3 解決:
在API代碼 APICommentService 中添加一個方法來替換原始碼中的序列化存盤
也就是你使用了下面的這個bean的代碼中

// 在保存是去除鍵名前面的十六進制,例如:\xac\xed\x00\x05t\x00\x0acomment-21 要保存的是acomment-21
// 這種特殊字符出現的原因,是因為RedisTemplate默認使用JdkSerializationRedisSerializer作為序列化工具
@Autowired(required = false)
public void setRedisTemplate(RedisTemplate redisTemplate) { // 這里直接把鍵值轉為string保存
RedisSerializer stringSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringSerializer);
redisTemplate.setHashKeySerializer(stringSerializer);
this.redisTemplate = redisTemplate;
}
加上上面代碼就可以將API保存在redis中的鍵名變為字串
2. 為什么API保存的鍵直接在第一級目錄下,而注解保存的是分級的,怎么讓他們共用同樣的資料,保存在同及目錄下?

上面的圖片是已經保存在一個目錄下的結果
comment是保存的表名,comment-id是保存的欄位
兩個冒號:: 表示子目錄
2.1 解決
在API代碼中修改代碼:
- 主要就是在1問題的基礎上,首先欄位要按照string來保存
- 就是在原先鍵的基礎上加上前綴 cacheName ::,來表示它是屬于cacheName目錄下的(也可以叫表)
private String cacheName = "comment::";
public CommentMain findById(int id) {
Object o = redisTemplate.opsForValue().get(cacheName + "comment-" + id);
if (o != null) {
return (CommentMain) o;
} else {
Optional<CommentMain> optionalCommentMain = commentRepository.findById(id);
if (optionalCommentMain.isPresent()) {
CommentMain commentMain = optionalCommentMain.get();
redisTemplate.opsForValue().set(cacheName+"comment-" + id, commentMain, 1, TimeUnit.DAYS);
return commentMain;
} else {
return null;
}
}
}
3. 盲僧:為什么在 cacheManager 使用json序列化的時候 鍵名上 多出了一個 “ ,

3.1 解決:
自己把代碼寫錯哦了

改成:

serializeKeysWith 使用字串
serializeValuesWith 使用json
這樣就可以 /xk
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/282568.html
標籤:其他
