当前位置: 移动技术网 > IT编程>开发语言>Java > SpringBoot中默认缓存实现方案的示例代码

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

2020年08月17日  | 移动技术网IT编程  | 我要评论
在上一节中,我带大家学习了详解springboot集成redis来实现缓存技术方案,尤其是结合spring cache的注解的实现方案,接下来在本章节中,我带大家通过代码来实现。一. spring b

在上一节中,我带大家学习了详解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中默认的缓存方案。

总结

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

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网