SpringBoot 在使用API和注解遇到的问题

2021/5/1 18:25:32

本文主要是介绍SpringBoot 在使用API和注解遇到的问题,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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. 主要就是在1问题的基础上,首先字段要按照string来保存
  2. 就是在原先键的基础上加上前缀 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



这篇关于SpringBoot 在使用API和注解遇到的问题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程