Springboot整合Redis手机验证码储存


Springboot整合Redis手机验证码储存

使用原始方式实现查询

application.yml

spring:
  datasource:
    url: jdbc:mysql:///springbootdata?serverTimezone=UTC&useUnicode=true&useSSL=true&characterEncoding=utf8
    username: root
    password: 1234
  jpa:
    show-sql: true

maven依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

实体类comment

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity(name = "t_comment") // 映射的数据库表名
public class Comment {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY) // 主键自增
    private Integer id;
    private String content;
    private String author;
    @Column(name = "a_id") // 对应的数据库列名
    private Integer aId;
}

mapper层

public interface CommentRepository extends JpaRepository<Comment, Integer> {
    // 根据id修改评论作者
    @Transactional // 更新的操作需要做事务控制
    @Modifying
    @Query("update t_comment c set c.author=?1 where c.id=?2")
    int updateComment(String author, Integer id);
}

service层

@Service
public class CommentService {

    @Autowired
    private CommentRepository commentRepository;
    public Comment findById(int comment_id){
        Optional<Comment> optional = commentRepository.findById(comment_id);
        if (optional.isPresent()){
            return optional.get();
        }
        return null;
    }
    public Comment updateComment(Comment comment){
        commentRepository.updateComment(comment.getAuthor(),comment.getId());
        return comment;
    }
    public void deleteComment(int comment_id){
        commentRepository.deleteById(comment_id);
    }
}

控制层

@Controller
@ResponseBody
public class CommentController {
    @Autowired
    private CommentService commentService;

    @RequestMapping("/get/{id}")
    public Comment findById(@PathVariable("id") int comment_id){
        Comment comment = commentService.findById(comment_id);
        return comment;
    }

    public Comment updateComment(@PathVariable("id")int comment_id,@PathVariable("author") String author){
        Comment comment = commentService.findById(comment_id);
        comment.setAuthor(author);
        Comment updateComment = commentService.updateComment(comment);
        return updateComment;
    }
    public void deleteComment(@PathVariable("id") int comment_id){
        commentService.deleteComment(comment_id);
    }
}

基于注解实现缓存

在主启动类上添加注解:@EnableCaching

该注解配置在类上,通常都是在主启动类上

在需要加缓存的方法上加一个注解:@Cacheable

@Cacheable(cacheNames = "comment") // 通常用过缓存数据
@CachePut(cacheNames = "comment", key = "#result.id") // 用作更新数据
@CacheEvict(cacheNames = "comment") // 用作删除缓存数据
@Service
public class CommentService {

    @Autowired
    private CommentRepository commentRepository;

    @Cacheable(cacheNames = "comment", unless = "#result==null")
    public Comment findById(int comment_id) {
        Optional<Comment> optional = commentRepository.findById(comment_id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    @CachePut(cacheNames = "comment", key = "#result.id")
    public Comment updateComment(Comment comment) {
        commentRepository.updateComment(comment.getAuthor(), comment.getId());
        return comment;
    }

    @CacheEvict(cacheNames = "comment")
    public void deleteComment(int comment_id) {
        commentRepository.deleteById(comment_id);
    }
}
@Controller
@ResponseBody
public class CommentController {
    @Autowired
    private CommentService commentService;

    @RequestMapping("/get/{id}")
    public Comment findById(@PathVariable("id") int comment_id){
        Comment comment = commentService.findById(comment_id);
        return comment;
    }

    @RequestMapping("/update/{id}/{author}")
    public Comment updateComment(@PathVariable("id")int comment_id,@PathVariable("author") String author){
        Comment comment = commentService.findById(comment_id);
        comment.setAuthor(author);
        Comment updateComment = commentService.updateComment(comment);
        return updateComment;
    }
    @RequestMapping("/{id}")
    public void deleteComment(@PathVariable("id") int comment_id){
        commentService.deleteComment(comment_id);
    }
}

基于API实现缓存

使用RedisTemplate

@Service
public class ApiCommentService {
    @Autowired
    private CommentRepository commentRepository;
    @Autowired
    private RedisTemplate redisTemplate;
    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();
                // 将查询结果放缓存中,时间为1天
                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.getId());
        // 更新数据后,将缓存数据也更新
        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
@ResponseBody
@RequestMapping("api")
public class ApiCommentController {
    @Autowired
    private ApiCommentService commentService;

    @RequestMapping("/get/{id}")
    public Comment findById(@PathVariable("id") int comment_id){
        Comment comment = commentService.findById(comment_id);
        return comment;
    }

    @RequestMapping("/update/{id}/{author}")
    public Comment updateComment(@PathVariable("id")int comment_id,@PathVariable("author") String author){
        Comment comment = commentService.findById(comment_id);
        comment.setAuthor(author);
        Comment updateComment = commentService.updateComment(comment);
        return updateComment;
    }
    @RequestMapping("/{id}")
    public void deleteComment(@PathVariable("id") int comment_id){
        commentService.deleteComment(comment_id);
    }
}

基于API自定义序列化缓存

上面的缓存机制是jdk,给我们的阅读造成了很大的困扰。我们可以考虑考虑使用自定义的缓存机制;

public class RedisAutoConfiguration {

   @Bean
   @ConditionalOnMissingBean(name = "redisTemplate")
   @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
   public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
      RedisTemplate<Object, Object> template = new RedisTemplate<>();
      template.setConnectionFactory(redisConnectionFactory);
      return template;
   }
}

我们可以参照这种写法来自定义一个序列化机制

RedisConfig.java

@Configuration
public class RedisConfig {
    public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        // 使用json格式序列化对象,对缓存数据key和value进行转换
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        // 解决查询缓存转换异常的问题
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);
        // 设置RedisTemplate模板API的序列化方式为json
        template.setDefaultSerializer(serializer);
        return template;
    }
}

基于注解自定义序列化缓存


文章作者: 夏梦
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 夏梦 !
 上一篇
mysql基础 mysql基础
##本单元目标 一、为什么要学习数据库 二、数据库的相关概念 DBMS、DB、SQL 三、数据库存储数据的特点 四、初始MySQL MySQL产品的介绍 MySQL产品的安装
2021-04-28 夏梦
下一篇 
Springboot整合Redis实现缓存 Springboot整合Redis实现缓存
Springboot整合Redis实现缓存使用原始方式实现查询application.yml spring: datasource: url: jdbc:mysql:///springbootdata?serverTimezon
2021-04-09
  目录