Spring Boot基于API的Redis缓存实现

本篇随笔基于https://blog.csdn.net/weixin_41842236/article/details/104205713实现

一、使用Redis API进行业务数据缓存管理

在service下新建ApiCommentService,删除原有的CommentService

 
package com.uos.cache.service;


import com.uos.cache.domain.Comment;
import com.uos.cache.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Service
public class ApiCommentService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CommentRepository commentRepository;
    public Comment findById(int comment_id){
        Object object =  redisTemplate.opsForValue().get("comment_"+comment_id);
        if (object!=null){
            return (Comment)object;}else {
            Optional<Comment> optional = commentRepository.findById(comment_id);
            if(optional.isPresent()){Comment comment= optional.get();
                redisTemplate.opsForValue().set("comment_"+comment_id,
                        comment,1, TimeUnit.DAYS);return comment;
            }else {return null;}
        }
    }
    public Comment updateComment(Comment comment){
        commentRepository.updateComment(comment.getAuthor(), comment.getaId());
        redisTemplate.opsForValue().set("comment_"+comment.getId(),comment);
        return comment;
    }
    public void deleteComment(int comment_id){
        commentRepository.deleteById(comment_id);
        redisTemplate.delete("comment_"+comment_id);
    }

}

 

二、在controller层下新建ApiCommentController

删除原有的CommentController

 
package com.uos.cache.controller;

import com.uos.cache.domain.Comment;
import com.uos.cache.service.ApiCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class ApiCommentController {
    @Autowired
    private ApiCommentService apiCommentService;
    @GetMapping("/get/{id}")
    public Comment findById(@PathVariable("id") int comment_id){
        Comment comment = apiCommentService.findById(comment_id);
        return comment;
    }
    @GetMapping("/update/{id}/{author}")
    public Comment updateComment(@PathVariable("id") int comment_id,
                                 @PathVariable("author") String author){
        Comment comment = apiCommentService.findById(comment_id);
        comment.setAuthor(author);
        Comment updateComment = apiCommentService.updateComment(comment);
        return updateComment;
    }
    @GetMapping("/delete/{id}")
    public void deleteComment(@PathVariable("id") int comment_id){
        apiCommentService.deleteComment(comment_id);
    }

}

 

三、主程序类

 

四、效果测试

查询测试

更新测试

 

 删除测试

 

      相对使用注解的方式,使用Redis API进行数据缓存管理更加灵活,例如,

手机验证码进行验证时,可以在缓存中设置验证等待时间。

     相比使用注解的方式进行缓存管理,使用Redis API的方式编写的代码量可能会更多。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 可以通过集成Spring Data Redis来添加Redis缓存Spring Data RedisSpring提供的一个用于操作Redis的开源库。要添加Redis缓存,可以按照以下几个步骤进行操作。 第一步,添加依赖: 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 这将自动引入Spring Data Redis及其相关依赖。 第二步,配置Redis连接信息: 在application.properties(或application.yml)文件中配置Redis连接信息,如下所示: ``` spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password= spring.redis.database=0 ``` 可以根据实际情况修改Redis的主机名、端口号、密码和数据库索引。 第三步,使用Redis缓存: 在需要使用Redis缓存的地方,可以使用Spring提供的注解进行缓存操作。例如,可以使用`@Cacheable`注解标记一个方法,表示该方法的结果将被缓存: ```java @Cacheable("myCache") public String getValue(String key) { // 从数据库或其他数据源中获取数据 return value; } ``` 在上面的例子中,`myCache`是缓存的名称,可以根据实际需要进行命名。当调用`getValue`方法时,如果缓存中已经有对应的数据,则直接从缓存中获取数据,否则会执行方法体内的代码,并将结果缓存起来。 需要注意的是,为了使`@Cacheable`注解生效,还需要在启动类上添加`@EnableCaching`注解,以启用缓存功能。 通过以上步骤,就可以在Spring Boot应用中添加Redis缓存,并使用Redis作为数据的缓存存储。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值