Redis---SpringCache(一)无参数使用

一.简介

Spring Cache 是Spring - context-xxx.jar中提供的功能,可以结合EHCache,Redis等缓存工具使用。给用户提供非常方便的缓存处理,缓存基本判断等操作,可以直接使用注解实现。

二.开启方式

在包含了Spring - context-xxx.jar的Spring Boot项目中,在启动类中添加@EnableCaching注解,即可开启缓存功能。默认Spring Cache是不开启。

三.SpringCache的优点

1.1正常情况下使用Redis缓存工具时代码流程:

在这里插入图片描述

1.2在使用SpringCache后

在代码方法中编写对数据库的访问。只需要完成上面流程图中“从mysql取出”部分的代码。剩余事情使用一个非常简单的注解即可,省略了访问redis取数据及把mysql数据缓存到redis的代码,让开发起来更简单。

2.SpringCache加载缓存工具顺序

只要检测到项目中配置了下面缓存工具。(导入了依赖,在Spring容器中发现对应工具的内容),无论导入多少个缓存工具用于只用最前面的一个。
1.Generic
2.JCache (JSR-107) (EhCache 3, Hazelcast, Infinispan, and others)
3.EhCache 2.x
4.Hazelcast
5.Infinispan
6.Couchbase
7.Redis
8.Caffeine
9.Simple

3.无参数使用

3.1在pom.xml中添加依赖

Spring-boot-starter-web和spring-boot-start-data-redis

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.7.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
</dependencies>
3.2新建配置文件

在application.yml中配置redis

spring:
  redis:
    host: 192.168.8.129
3.3新建启动类
@SpringBootApplication
@EnableCaching
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class,args);
    }
}
3.4新建Service和实现类
3.4.1 每个方法单独配置key前缀

每个方法单独配置key前缀适用于整个类中方法的前缀不统一的情况。
@Cacheable表示要对方法返回值进行缓存。缓存时key的名称为
cacheNames : 配置key的前缀
key:配置key的后缀。里面字符串要使用单引号。
Spring Cache使用的RedisTemplate<StringRedisSerializer,JdkSerializationRedisSerializer>

public interface DemoService {
    String demo();
}
@Service
public class DemoServiceImpl implements DemoService {
    @Override
    // 固定字符串需要使用单引号
    @Cacheable(key = "'demo'",cacheNames = "com.yrp")
    public String demo() {
        System.out.println("demo方法被执行");
        return "demo-result";
    }
}
3.4.2 统一配置类中方法前缀

一般情况下一个类中方法的对应key的前缀都是一样,可以把前缀cacheNames提出到类上,统一配置。

public interface DemoService {
    String demo();
}
@Service
@CacheConfig(cacheNames = "com.bjsxt")
public class DemoServiceImpl implements DemoService {
    @Override
    // 固定字符串需要使用单引号
    @Cacheable(key = "'demo'")
    public String demo() {
        System.out.println("demo方法被执行");
        return "demo-result";
    }
}
3.5新建控制器
@Controller
public class DemoConteroller {
    @Autowired
    private DemoService demoService;
    @RequestMapping("/demo")
    @ResponseBody
    public String demo(){
        return demoService.demo();
    }
}
3.6测试结果

在浏览器中访问/demo后会发现控制台打印“demo方法被执行”,通过redis中出现com.bjsxt::demo的key
再次访问,控制台不会被打印,说明执行缓存。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值