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
0
投稿
猜你喜欢
- 先看Demo运行效果SharedPreferences详解SharedPreferences是Android平台上一个轻量级的存储类,用来保
- 一、项目要求实现一个通讯录通讯录可以用来存储100个人的信息,每个人的信息包括:姓名、性别、年龄、电话、住址提供方法:添加联系人信息删除指定
- 附GitHub源码:WebViewExplore一、WebView的基础配置WebSettings ws = getSettings();w
- 本文实例为大家分享了java实现微信扫码支付的具体代码,供大家参考,具体内容如下1、maven项目的pom.xml中添加如下jar包:<
- 微服务feign调用添加token1.一般情况是这么配置的具体的怎么调用就不说了 如下配置,就可以在请求头中添加需要的请求头信息。packa
- 本文为大家分享了JAVA语言课程设计:连连看小游戏,供大家参考,具体内容如下1.设计内容界面中有5*10的界面,图中共有6种不同的图片,每两
- 如果不知道,类的静态变量存储在那? 方法的局部变量存储在那? 赶快收藏Java内存区域主要可以分为共享内存,堆、方法区和线程私有内存,虚拟机
- 1、前言最近在用Kotlin+Spring Boot写一个后端项目,实体类习惯性地用了Kotlin中的data class,但是Spring
- 在项目迁移到Spring Boot之后,发生内存使用量过高的问题。本文介绍了整个排查过程以及使用到的工具,也非常适用于其他堆外内存排查。背景
- 前言:mongodb是一个基于分布式文件存储的开源数据库系统。mongodb与我们平常使用的mysql的区别: 1.
- Console.WriteLine("This is a Client, host name is {0}", Dns.
- 过年微信红包很火,最近有个项目也要做抢红包,于是写了个红包的生成算法。红包生成算法的需求预先生成所有的红包还是一个请求随机生成一个红包简单来
- 本文实例讲述了Java单例模式下的MongoDB数据库操作工具类。分享给大家供大家参考,具体如下:我经常对MongoDB进行一些基础操作,将
- SpringCloud 整合ribbon的时候出现了这个问题java.lang.IllegalStateException: No inst
- 最近看spring的JDBCTemplete的模板方式调用时,对模板和回调产生了浓厚兴趣,查询了一些资料,做一些总结。回调函数:所谓回调,就
- Condition的作用是对锁进行更精确的控制。Condition中的await()方法相当于Object的wait()方法,Conditi
- 部署到webapps目录启动本文使用的Spring版本为Spring6,SpringBoot版本为3,JDK为17,可能会和之前有细微不同,
- 模板消息文档公众号的类型分为服务号、订阅号和企业号,其中服务号和订阅号比较常见。要想实现公众号推动消息给指定的用户,其类型必须为服务号。推送
- 写在前面在前后端交互过程中,为了保证信息安全,我们往往需要加点用户验证。本文介绍了用springboot简单整合token。springbo
- 顺序语句顺序顾名思义就是程序自上而下执行public class User { public static voi