SpringBoot整合Redis使用注解方式设置缓存

Spring Cache使用方法与Spring对事务管理的配置相似。SpringCache的核心就是对某个方法进行缓存,其实质就是缓存该方法的返回结果,并把方法参数和结果用键值对的方式存放到缓存中,当再次调用该方法使用相应的参数时,就会直接从缓存里面取出指定的结果进行返回

那么使用 Redistemplate 和 使用注解有什么区别呢?

  1. 区别就是 Redistemplate 偏向于底层,可以设置缓存时间等其他操作
  2. 使用注解方式不能设置缓存时间,只是简单地存储和删除缓存操作
  3. 那么这么做的目的就是因为Springboot更偏向于工具的兼容性

1. 常用注解

  1. @EnableCaching : 开启缓存支持
  2. @Cacheable : 使用这个注解的方法在执行后会缓存其返回结果(存储数据到缓存)
  3. @CacheEvict : 使用这个注解的方法在其执行前或执行后移除Spring Cache中的某些元素(删除缓存)

2. 环境配置

pom.xml

     <!--redis 配置-->
	  <dependency>
		  <groupId>org.springframework.boot</groupId>
		  <artifactId>spring-boot-starter-data-redis</artifactId>
	  </dependency>

application.yml

server:
  port: 9005
spring:
  datasource:
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/xxx?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: root
  jpa:
    database: MySQL
    show-sql: true
  redis: # redis配置,如果端口号是6379默认端口,那么只需要写地址就行
      host: 123.56.153.90

3. 使用缓存

3.1 Application启动类

添加注解 @EnableCaching 开启缓存支持

package com.tensquare.gathering;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class GatheringApplication {
	public static void main(String[] args) {
		SpringApplication.run(GatheringApplication.class, args);
	}
}

3.2 缓存添加

示例 : 在执行按ID查询操作时,添加数据到缓存中

 /**
     * 根据ID查询实体
     * @Cacheable : 把返回结果添加到缓存中
     * (value = "gathering",key = "#id") 
	 * value就是键的名称
	 * key是数据加密的盐
	 * #id 使用参数中的id作为盐
	 * 需求: 把findById返回的结果添加到缓存中
     */
    @Cacheable(value = "gathering", key = "#id")
    public Gathering findById(String id) {
        return gatheringDao.findById(id).get();
    }

3.3 缓存删除

 /**
	 * @CacheEvict : 调用方法时删除缓存
	 * (value = "gathering", key = "#gathering.id")
	 * value就是键的名称
	 * key是数据加密的盐,
	 * #gathering.id 使用参数中的id作为盐
	 * 需求: 执行修改方法时,把 key为 gathering 的缓存删除
	 */
    @CacheEvict(value = "gathering", key = "#gathering.id")
    public void update(Gathering gathering) {
        gatheringDao.save(gathering);
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

叫我三胖哥哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值