SpringBoot @Cacheable简单使用

导读:本篇文章讲解 SpringBoot @Cacheable简单使用,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

@Cacheable

官方例子
官方文档
简单来说:Spring将会拦截我们的目标方法,检查是否之前已经调用过。如果调用过,则会返回缓存值的副本。否则,将会执行目标方法、存储返回值到缓存中,最后返回值。

流程

有一张类似support data的数据表,里面的数据基本上不会变化。在取这张表的数据时,会根据传入的参数进行一些逻辑判断,在参数一定的前提下,返回的数据是一样的。

准备数据库

create table t_dictionaries
(
  id int not null primary key,
  name varchar(45) null
);

INSERT INTO t_dictionaries (id, name) VALUES (1, 'man');
INSERT INTO t_dictionaries (id, name) VALUES (2, 'woman');

导入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.20</version>
    <scope>provided</scope>
</dependency>        

启动类

@SpringBootApplication
// 别忘了@EnableCaching
@EnableCaching
public class TodolistApplication {
    public static void main(String[] args) {
        SpringApplication.run(TodolistApplication.class, args);
    }
}

controller层

@RestController
public class DictionaryController {
    @Autowired
    private DictionaryService dictionaryService;

    @GetMapping(value = "/dictionary")
    public Dictionary getDictionary(int id) {
        return dictionaryService.getDictionaryById(id);
    }
}

service层

@Service
public class DictionaryServiceImpl implements DictionaryService {

    @Autowired
    private DictionaryCache dictionaryCache;

    @Override
    public Dictionary getDictionaryById(int id) {
        System.out.println("Call dictionaryCache#findDictionaryById");
        Dictionary dictionary = dictionaryCache.findDictionaryById(id);
        System.out.println("return value: " + dictionary.toString());
        return dictionary;
    }
}

Cache

当传入的参数和之前一样时,不执行方法区,直接返回值。

@Component
public class DictionaryCache {

    @Autowired
    private DictionaryRepository dictionaryRepository;

    @Cacheable(value = "dictionaryList")
    public Dictionary findDictionaryById(int id) {
        System.out.println("Target Id: " + id);
        return dictionaryRepository
                .findById(id)
                .orElse(null);
    }
}

测试

第一次调用,传入id = 1
在这里插入图片描述第二次调用,传入id = 1
没有再次访问数据库,且返回相同的数据
在这里插入图片描述第三次调用,传入id = 2
再次访问数据库,并返回目标数据
在这里插入图片描述

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

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/77921.html

(0)
小半的头像小半

相关推荐

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