热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

开启注解缓存_SpringBoot2.x系列教程57SpringBoot中默认缓存实现方案

SpringBoot2.x系列教程57--SpringBoot中默认缓存实现方案作者:一一哥在上一节中,我带大家学习了在SpringBoot中对缓存的实

SpringBoot2.x系列教程57--SpringBoot中默认缓存实现方案

作者:一一哥

在上一节中,我带大家学习了在Spring Boot中对缓存的实现方案,尤其是结合Spring Cache的注解的实现方案,接下来在本章节中,我带大家通过代码来实现。

一. Spring Boot实现默认缓存

1. 创建web项目

我们按照之前的经验,创建一个web程序,并将之改造成Spring Boot项目,具体过程略。

0c11add4e00f12a086cf4ee5789aa982.png

2. 添加依赖包

org.springframework.bootspring-boot-starter-data-jpa
mysqlmysql-connector-java
org.springframework.bootspring-boot-starter-cache

3. 创建application.yml配置文件

server:port: 8080
spring:application:name: cache-demodatasource:driver-class-name: com.mysql.cj.jdbc.Driverusername: rootpassword: sycurl: jdbc:mysql://localhost:3306/spring-security?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false&serverTimezone=UTC#cache:#type: generic #由redis进行缓存,一共有10种缓存方案jpa:database: mysqlshow-sql: true #开发阶段,打印要执行的sql语句.hibernate:ddl-auto: update

4. 创建一个缓存配置类

主要是在该类上添加@EnableCaching注解,开启缓存功能。

package com.yyg.boot.config;import org.springframework.cache.annotation.EnableCaching;/*** @Author 一一哥Sun* @Date Created in 2020/4/14* @Description Description* EnableCaching启用缓存*/
@Configuration
@EnableCaching
public class CacheConfig {
}

5. 创建User实体类

package com.yyg.boot.domain;import lombok.Data;
import lombok.ToString;import javax.persistence.*;
import java.io.Serializable;@Entity
@Table(name="user")
@Data
@ToString
public class User implements Serializable {//IllegalArgumentException: DefaultSerializer requires a Serializable payload// but received an object of type [com.syc.redis.domain.User]@Id@GeneratedValue(strategy = GenerationType.AUTO)private Long id;@Columnprivate String username;@Columnprivate String password;}

6. 创建User仓库类

package com.yyg.boot.repository;import com.yyg.boot.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;public interface UserRepository extends JpaRepository {
}

7. 创建Service服务类

定义UserService接口

package com.yyg.boot.service;import com.yyg.boot.domain.User;public interface UserService {User findById(Long id);User save(User user);void deleteById(Long id);}

实现UserServiceImpl类

package com.yyg.boot.service.impl;import com.yyg.boot.domain.User;
import com.yyg.boot.repository.UserRepository;
import com.yyg.boot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;@Service
public class UserServiceImpl implements UserService {@Autowiredprivate UserRepository userRepository;//普通的缓存+数据库查询代码实现逻辑://User user=RedisUtil.get(key);// if(user==null){// user=userDao.findById(id);// //redis的key="product_item_"+id// RedisUtil.set(key,user);// }// return user;/*** 注解@Cacheable:查询的时候才使用该注解!* 注意:在Cacheable注解中支持EL表达式* redis缓存的key=user_1/2/3....* redis的缓存雪崩,缓存穿透,缓存预热,缓存更新...* condition = "#result ne null",条件表达式,当满足某个条件的时候才进行缓存* unless = "#result eq null":当user对象为空的时候,不进行缓存*/@Cacheable(value = "user", key = "#id", unless = "#result eq null")@Overridepublic User findById(Long id) {return userRepository.findById(id).orElse(null);}/*** 注解@CachePut:一般用在添加和修改方法中* 既往数据库中添加一个新的对象,于此同时也往redis缓存中添加一个对应的缓存.* 这样可以达到缓存预热的目的.*/@CachePut(value = "user", key = "#result.id", unless = "#result eq null")@Overridepublic User save(User user) {return userRepository.save(user);}/*** CacheEvict:一般用在删除方法中*/@CacheEvict(value = "user", key = "#id")@Overridepublic void deleteById(Long id) {userRepository.deleteById(id);}}

8. 创建Controller接口方法

package com.yyg.boot.web;import com.yyg.boot.domain.User;
import com.yyg.boot.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {&#64;Autowiredprivate UserService userService;&#64;PostMappingpublic User saveUser(&#64;RequestBody User user) {return userService.save(user);}&#64;GetMapping("/{id}")public ResponseEntity getUserById(&#64;PathVariable("id") Long id) {User user &#61; userService.findById(id);log.warn("user&#61;"&#43;user.hashCode());HttpStatus status &#61; user &#61;&#61; null ? HttpStatus.NOT_FOUND : HttpStatus.OK;return new ResponseEntity<>(user, status);}&#64;DeleteMapping("/{id}")public String removeUser(&#64;PathVariable("id") Long id) {userService.deleteById(id);return "ok";}}

9. 创建入口类

package com.yyg.boot;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;&#64;SpringBootApplication
public class CacheApplication {public static void main(String[] args) {SpringApplication.run(CacheApplication.class, args);}}

10. 完整项目结构

8f639ca87d9074a410bca3948637411b.png

11. 启动项目进行测试

我们首先调用添加接口&#xff0c;往数据库中添加一条数据。

f25eba87081c66acb2ee810b18404a06.png

可以看到数据库中&#xff0c;已经成功的添加了一条数据。

cf0b1cdf06193ff101eadde4a582bd57.png

&#xfffc;然后测试一下查询接口方法。

cf0b1cdf06193ff101eadde4a582bd57.png

&#xfffc;此时控制台打印的User对象的hashCode如下:

5ea35ca19a715211ef85dad478c83878.png

&#xfffc;我们再多次执行查询接口&#xff0c;发现User对象的hashCode值不变&#xff0c;说明数据都是来自于缓存&#xff0c;而不是每次都重新查询。

66d855431285caef0eb3bb3cac61435f.png

&#xfffc;至此&#xff0c;我们就实现了Spring Boot中默认的缓存方案。



推荐阅读
  • http:my.oschina.netleejun2005blog136820刚看到群里又有同学在说HTTP协议下的Get请求参数长度是有大小限制的,最大不能超过XX ... [详细]
  • 自动轮播,反转播放的ViewPagerAdapter的使用方法和效果展示
    本文介绍了如何使用自动轮播、反转播放的ViewPagerAdapter,并展示了其效果。该ViewPagerAdapter支持无限循环、触摸暂停、切换缩放等功能。同时提供了使用GIF.gif的示例和github地址。通过LoopFragmentPagerAdapter类的getActualCount、getActualItem和getActualPagerTitle方法可以实现自定义的循环效果和标题展示。 ... [详细]
  • 本文介绍了关系型数据库和NoSQL数据库的概念和特点,列举了主流的关系型数据库和NoSQL数据库,同时描述了它们在新闻、电商抢购信息和微博热点信息等场景中的应用。此外,还提供了MySQL配置文件的相关内容。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • PHP设置MySQL字符集的方法及使用mysqli_set_charset函数
    本文介绍了PHP设置MySQL字符集的方法,详细介绍了使用mysqli_set_charset函数来规定与数据库服务器进行数据传送时要使用的字符集。通过示例代码演示了如何设置默认客户端字符集。 ... [详细]
  • Metasploit攻击渗透实践
    本文介绍了Metasploit攻击渗透实践的内容和要求,包括主动攻击、针对浏览器和客户端的攻击,以及成功应用辅助模块的实践过程。其中涉及使用Hydra在不知道密码的情况下攻击metsploit2靶机获取密码,以及攻击浏览器中的tomcat服务的具体步骤。同时还讲解了爆破密码的方法和设置攻击目标主机的相关参数。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • 计算机存储系统的层次结构及其优势
    本文介绍了计算机存储系统的层次结构,包括高速缓存、主存储器和辅助存储器三个层次。通过分层存储数据可以提高程序的执行效率。计算机存储系统的层次结构将各种不同存储容量、存取速度和价格的存储器有机组合成整体,形成可寻址存储空间比主存储器空间大得多的存储整体。由于辅助存储器容量大、价格低,使得整体存储系统的平均价格降低。同时,高速缓存的存取速度可以和CPU的工作速度相匹配,进一步提高程序执行效率。 ... [详细]
  • yum安装_Redis —yum安装全过程
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了Redis—yum安装全过程相关的知识,希望对你有一定的参考价值。访问https://redi ... [详细]
  • 篇首语:本文由编程笔记#小编为大家整理,主要介绍了软件测试知识点之数据库压力测试方法小结相关的知识,希望对你有一定的参考价值。 ... [详细]
  • 全面介绍Windows内存管理机制及C++内存分配实例(四):内存映射文件
    本文旨在全面介绍Windows内存管理机制及C++内存分配实例中的内存映射文件。通过对内存映射文件的使用场合和与虚拟内存的区别进行解析,帮助读者更好地理解操作系统的内存管理机制。同时,本文还提供了相关章节的链接,方便读者深入学习Windows内存管理及C++内存分配实例的其他内容。 ... [详细]
  • 本文介绍了如何在Azure应用服务实例上获取.NetCore 3.0+的支持。作者分享了自己在将代码升级为使用.NET Core 3.0时遇到的问题,并提供了解决方法。文章还介绍了在部署过程中使用Kudu构建的方法,并指出了可能出现的错误。此外,还介绍了开发者应用服务计划和免费产品应用服务计划在不同地区的运行情况。最后,文章指出了当前的.NET SDK不支持目标为.NET Core 3.0的问题,并提供了解决方案。 ... [详细]
  • Spring框架《一》简介
    Spring框架《一》1.Spring概述1.1简介1.2Spring模板二、IOC容器和Bean1.IOC和DI简介2.三种通过类型获取bean3.给bean的属性赋值3.1依赖 ... [详细]
  • Jboss的EJB部署描述符standardjaws.xml配置步骤详解
    本文详细介绍了Jboss的EJB部署描述符standardjaws.xml的配置步骤,包括映射CMP实体EJB、数据源连接池的获取以及数据库配置等内容。 ... [详细]
  • 本文介绍了解决java开源项目apache commons email简单使用报错的方法,包括使用正确的JAR包和正确的代码配置,以及相关参数的设置。详细介绍了如何使用apache commons email发送邮件。 ... [详细]
author-avatar
轻淞猪
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有