Spring Boot 缓存介绍 与 Spring Cache基本用法

导读:本篇文章讲解 Spring Boot 缓存介绍 与 Spring Cache基本用法,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

🎈博客主页:🌈我的主页🌈
🎈欢迎点赞 👍 收藏 🌟留言 📝 欢迎讨论!👏
🎈本文由 【泠青沼~】 原创,首发于 CSDN🚩🚩🚩
🎈由于博主是在学小白一枚,难免会有错误,有任何问题欢迎评论区留言指出,感激不尽!🌠个人主页



🌟 一、Java缓存框架

  • EhCache

Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点

  • Spring Cache

它并不是具体的实现,而是一个对缓存的抽象

举个例子:

抽象(规范) 具体实现
JDBC MYSQL驱动
Spring Cache EhCache
JPA Hibernate

定义一个上层的规范,让所有的实现类都去实现规范,最如果实现类需要改变只需要改变实现类部分,核心的内部代码不需要改变,对于开发者来说就只需要实现规范的接口,更换依赖项就可以完成

🌟 二、Spring Cache 用法

  • @EnableCaching
  • @Cacheable
  • @CachePut
  • @CacheEvict
  • @Caching
  • @CacheConfig

🌟 三、@EnableCaching

在这里插入图片描述

boolean proxyTargetClass() default false;
//设置使用的代理方式,默认jdk的动态代理,如果为true就是cjlib的动态代理

🌟 四、Spring Cache基本用法

🌟🌟 4.1、Maven添加POM依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

🌟🌟 4.2、application.properties配置redis

spring.redis.host=127.0.0.1
spring.redis.port=6379

🌟🌟 4.3、配置实体类和业务类

实体类:

public class User implements Serializable {
    private String username;
    private Long id;

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", id=" + id +
                '}';
    }

业务类:

@Service
public class UserService {

    @Cacheable(cacheNames = "c1")//标记在方法上,表示该方法的返回结果需要缓存,
    // 默认是方法的参数作为redis缓存的key
    //触发缓存校验,若果缓存中没有,那就加入缓存,如果有直接取出来
    public User getUserByid(Long id){
        System.out.println("getUserByid:"+id);
        User user = new User();
        user.setId(id);
        user.setUsername("dong");
        return user;
    }
}

🌟🌟 4.4、单元测试

class CacheRedisApplicationTests {

    @Autowired
    UserService userService;

    @Test
    void contextLoads() {
        for (int i=0;i<3;i++){
            User u = userService.getUserByid(99L);
            System.out.println("u:"+u);
        }
    }

}

🌟🌟 4.5、运行结果

如果我们注释掉业务方法上的注解@Cacheable,结果:
在这里插入图片描述

方法被调用了三次,返回值没有被缓存

我们再重新加上业务方法上的注解@Cacheable,结果:

在这里插入图片描述

我们发现方法getUserByid()就只调用了一次,之后的调用只是从redis的缓存中读取数据,并且redis的键增加了@Cacheable中的参数“c1”,值就是方法返回的结果

在这里插入图片描述


版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/15734.html

(0)

相关推荐

半码博客——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!