SpringBoot中默认缓存实现方案的示例代码
作者:qfchenjunbo 发布时间:2023-11-24 05:50:30
标签:SpringBoot,默认缓存
在上一节中,我带大家学习了详解SpringBoot集成Redis来实现缓存技术方案,尤其是结合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中默认的缓存方案。
来源:https://blog.csdn.net/qfchenjunbo/article/details/107979677


猜你喜欢
- List 的方法列表方法名功能说明ArrayList()构造方法,用于创建一个空的数组列表add(E e)将指定的元素添加到此列表的尾部ge
- 在项目开发中,经常会碰到日期处理。比如查询中,可能会经常遇到按时间段查询,有时会默认取出一个月的数据。当我们提交数据时,会需要记录当前日期,
- volatile 变量提供了线程的可见性,并不能保证线程安全性和原子性。什么是线程的可见性:锁提供了两种主要特性:互斥(mutual exc
- 一、简介 1、地图 地图展示:普通地图(2D,3D)、卫星图和实时交通图。 地图操作:可通过接口或手势控制来实
- 本文实例讲述了Android中AlertDialog显示简单和复杂列表的方法。分享给大家供大家参考,具体如下:AlertDialog 显示简
- 我们都知道现在的语音合成TTS是可以通过微软的SAPI实现的,好处我就不多说了,方便而已,因为在微软的操作系统里面就自带了这个玩意,主要的方
- 一:模式说明模式定义:使多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求
- @RestControllerAdvice与@ControllerAdvice的区别@RestControllerAdvice注解与@Con
- 对接前端后效果展示如图:1、CPU相关信息实体类/** * CPU相关信息 * * @author csp */public class
- 冒泡排序:就是按索引逐次比较相邻的两个元素,如果大于/小于(取决于需要升序排还是降序排),则置换,否则不做改变这样一轮下来,比较了n-1次,
- 本文实例讲述了Java实现SSL双向认证的方法。分享给大家供大家参考,具体如下:我们常见的SSL验证较多的只是验证我们的服务器是否是真实正确
- 什么是SkyWalking查看官网https://skywalking.apache.org/分布式系统的应用程序性能监视工具,专为微服务、
- 1.第一种方式采用System.Net.Dns的GetHostAddress的方式,具体请看代码:/// <summary> &
- 上一篇中说到了 Expression 的一些概念性东西,其实也是为了这一篇做知识准备。为了实现 EFCore 的多条件、连表查询,简化查询代
- android跑马灯出现重复跳动、不滚动问题,本文给出解决方案,供大家参考。原因:页面有View被重新绘制了、焦点被抢占例如:1、TextV
- 一款书籍阅读器,需要以下功能才能说的上比较完整:文字页面展示,即书页;页面之间的跳转动画,即翻页动作;能够在每一页上记录阅读进度,即书签;能
- 参考:How to catch an Exception from a threadIs there a way to make Runna
- Java中的比较问题是一个很基础又很容易混淆的问题。今天就几个容易出错的点作一个比较详细的归纳与整理,希望对大家的学习与面试有帮助。一、==
- \r与\n到底有何区别,编码的时候又应该如何使用,我们下面来了解一下。区别:\r:全称:carriage return (carriage是
- springboot项目不配置数据源启动报错spring boot默认会加载org.springframework.boot.autocon