首页 > 其他分享 >SpringBoot2.x系列教程57--SpringBoot中默认缓存实现方案

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

时间:2022-12-23 18:04:11浏览次数:43  
标签:缓存 SpringBoot -- 57 boot user import id User


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

作者:一一哥

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

一. Spring Boot实现默认缓存

1. 创建web项目

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

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


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. 完整项目结构

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


11. 启动项目进行测试

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

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

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

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

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

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


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

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

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

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


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

标签:缓存,SpringBoot,--,57,boot,user,import,id,User
From: https://blog.51cto.com/u_7044146/5966090

相关文章

  • SpringBoot2.x系列教程56--SpringBoot中的缓存实现方案介绍
    SpringBoot2.x系列教程56--SpringBoot中的缓存实现方案介绍作者:一一哥一.Spring中对缓存的支持1.SpringCache简介从Spring3.1开始,Spring中引入了对Cache的支持。而在Spri......
  • SpringBoot2.x系列教程36--整合SpringMVC之CORS跨域访问处理(上)
    SpringBoot2.x系列教程36--整合SpringMVC之CORS跨域访问处理(上)作者:一一哥一.跨域问题及解决1.什么是跨域访问?JavaScript出于安全方面的考虑,做了一个同源策略的限制,也就......
  • 解决表单action属性传参时值为null的问题
    一.异常重现最近壹哥有个学生在学习Servlet进行Web开发时,尝试着使用表单中的action传递参数,结果他发现在Servlet中无法接收到前端传过来的参数值。我们先来看看他的代码,具......
  • 关于jsjiami.v6加密和解密
    JavaScript解密是指在JavaScript代码被加密之后,使用特定的工具或方法来恢复其原有的可读性。这种技术通常用于对JavaScript代码进行保护,以防止代码被未经授权的人窃取......
  • 冒泡排序
    冒泡排序只会操作相邻的两个数据。每次冒泡操作都会对相邻的两个元素进行比较,看是否满足大小关系要求。如果不满足就让它俩互换。一次冒泡会让至少一个元素移动到它应......
  • 如何理解动态规划
    一、动态规划三板斧状态转移公式循环或递归性能优化二、WHY1、状态转移公式动态规划与分治不一样,分治的问题是相互独立的,而动态规划的各个状态是有关联关系......
  • 初学java懵了,这个异常是怎么产生的?
    一.异常现象最近壹哥的老表开始学Java啦,结果学了还不到两天,就遇到了他解决不了的问题,然后就跑来问我了。不知有没有其他初学java的小伙伴,大家可以过来围观一下,看看下面的问......
  • 对Integer进行等值比较时踩到的一个坑
    一.引言小伙伴们应该都知道,只要我们写代码,必然就会有BUG的存在。所以解决BUG的过程会伴随程序员的一生,这就是一个无解的常态。在平时的学习和工作过程中,我们需要通过不断地实......
  • BMP格式详解
    BMP文件格式详解(BMPfileformat)BMP文件格式,又称为Bitmap(位图)或是DIB(Device-IndependentDevice,设备无关位图),是Windows系统中广泛使用的图像文件格式。由于它可以不作......
  • 集合泛型不匹配导致的ClassCastException异常解决
    一.代码重现前几天壹哥的一个学生小K编写集合代码时,运行的结果中却出现了一个自己没见过的异常,他不知道怎么解决,于是就跑来找壹哥帮忙。下面就是小K的代码,大家可以来看看,如......