SpringBoot中默认缓存实现方案的示例代码

 更新时间:2020年8月14日 08:51  点击:2305

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

一. Spring Boot实现默认缓存

1. 创建web项目

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

2. 添加依赖包

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
 
<dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
</dependency>
 
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

3. 创建application.yml配置文件

server:
 port: 8080
spring:
 application:
 name: cache-demo
 datasource:
 driver-class-name: com.mysql.cj.jdbc.Driver
 username: root
 password: syc
 url: jdbc:mysql://localhost:3306/spring-security?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false&serverTimezone=UTC
 #cache:
 #type: generic #由redis进行缓存,一共有10种缓存方案
 jpa:
 database: mysql
 show-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;
 
 @Column
 private String username;
 
 @Column
 private 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<User,Long> {
}

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 {
 
 @Autowired
 private 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")
 @Override
 public User findById(Long id) {
 
  return userRepository.findById(id).orElse(null);
 }
 
 /**
  * 注解@CachePut:一般用在添加和修改方法中
  * 既往数据库中添加一个新的对象,于此同时也往redis缓存中添加一个对应的缓存.
  * 这样可以达到缓存预热的目的.
  */
 @CachePut(value = "user", key = "#result.id", unless = "#result eq null")
 @Override
 public User save(User user) {
  return userRepository.save(user);
 }
 
 /**
  * CacheEvict:一般用在删除方法中
  */
 @CacheEvict(value = "user", key = "#id")
 @Override
 public 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 {
 
 @Autowired
 private UserService userService;
 
 @PostMapping
 public User saveUser(@RequestBody User user) {
  return userService.save(user);
 }
 
 @GetMapping("/{id}")
 public ResponseEntity<User> getUserById(@PathVariable("id") Long id) {
  User user = userService.findById(id);
  log.warn("user="+user.hashCode());
  HttpStatus status = user == null ? HttpStatus.NOT_FOUND : HttpStatus.OK;
  return new ResponseEntity<>(user, status);
 }
 
 @DeleteMapping("/{id}")
 public String removeUser(@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;
 
@SpringBootApplication
public class CacheApplication {
 
 public static void main(String[] args) {
  SpringApplication.run(CacheApplication.class, args);
 }
 
}

10. 完整项目结构

11. 启动项目进行测试

我们首先调用添加接口,往数据库中添加一条数据。

可以看到数据库中,已经成功的添加了一条数据。

然后测试一下查询接口方法。

此时控制台打印的User对象的hashCode如下:

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

至此,我们就实现了Spring Boot中默认的缓存方案。

总结

到此这篇关于SpringBoot中默认缓存实现方案的示例代码的文章就介绍到这了,更多相关SpringBoot默认缓存内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

[!--infotagslink--]

相关文章

  • 解决springboot使用logback日志出现LOG_PATH_IS_UNDEFINED文件夹的问题

    这篇文章主要介绍了解决springboot使用logback日志出现LOG_PATH_IS_UNDEFINED文件夹的问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-04-28
  • SpringBoot实现excel文件生成和下载

    这篇文章主要为大家详细介绍了SpringBoot实现excel文件生成和下载,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-09
  • 详解springBoot启动时找不到或无法加载主类解决办法

    这篇文章主要介绍了详解springBoot启动时找不到或无法加载主类解决办法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-09-16
  • SpringBoot集成Redis实现消息队列的方法

    这篇文章主要介绍了SpringBoot集成Redis实现消息队列的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-10
  • 解决Springboot get请求是参数过长的情况

    这篇文章主要介绍了解决Springboot get请求是参数过长的情况,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-09-17
  • Spring Boot项目@RestController使用重定向redirect方式

    这篇文章主要介绍了Spring Boot项目@RestController使用重定向redirect方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-02
  • Springboot+TCP监听服务器搭建过程图解

    这篇文章主要介绍了Springboot+TCP监听服务器搭建过程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-10-28
  • springBoot 项目排除数据库启动方式

    这篇文章主要介绍了springBoot 项目排除数据库启动方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-10
  • 详解SpringBoot之访问静态资源(webapp...)

    这篇文章主要介绍了详解SpringBoot之访问静态资源(webapp...),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-09-14
  • SpringBoot接口接收json参数解析

    这篇文章主要介绍了SpringBoot接口接收json参数解析,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-10-19
  • springboot中使用@Transactional注解事物不生效的坑

    这篇文章主要介绍了springboot中使用@Transactional注解事物不生效的原因,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-01-26
  • springboot多模块包扫描问题的解决方法

    这篇文章主要介绍了springboot多模块包扫描问题的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-09-16
  • Springboot mybatis plus druid多数据源解决方案 dynamic-datasource的使用详解

    这篇文章主要介绍了Springboot mybatis plus druid多数据源解决方案 dynamic-datasource的使用,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-11-18
  • Springboot实现多线程注入bean的工具类操作

    这篇文章主要介绍了Springboot实现多线程注入bean的工具类操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-08-27
  • Springboot+MDC+traceId日志中打印唯一traceId

    本文主要介绍了Springboot+MDC+traceId日志中打印唯一traceId,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-10-17
  • SpringBoot部署到Linux读取resources下的文件及遇到的坑

    本文主要给大家介绍SpringBoot部署到Linux读取resources下的文件,在平时业务开发过程中,很多朋友在获取到文件内容乱码或者文件读取不到的问题,今天给大家分享小编遇到的坑及处理方案,感兴趣的朋友跟随小编一起看看吧...2021-06-21
  • 关于springboot中nacos动态路由的配置

    这篇文章主要介绍了springboot中nacos动态路由的配置方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-11
  • SpringBoot高版本修改为低版本时测试类报错的解决方案

    这篇文章主要介绍了SpringBoot高版本修改为低版本时测试类报错的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-18
  • 解决Springboot整合shiro时静态资源被拦截的问题

    这篇文章主要介绍了解决Springboot整合shiro时静态资源被拦截的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-01-26
  • 详解SpringBoot读取配置文件的N种方法

    这篇文章主要介绍了详解SpringBoot读取配置文件的N种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-10