SpringBoot中默认缓存实现方案的示例代码
在上一节中,我带大家学习了详解SpringBoot集成Redis来实现缓存技术方案,尤其是结合SpringCache的注解的实现方案,接下来在本章节中,我带大家通过代码来实现。
一.SpringBoot实现默认缓存
1.创建web项目
我们按照之前的经验,创建一个web程序,并将之改造成SpringBoot项目,具体过程略。
2.添加依赖包
org.springframework.boot spring-boot-starter-data-jpa mysql mysql-connector-java org.springframework.boot spring-boot-starter-cache
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注解,开启缓存功能。
packagecom.yyg.boot.config; importorg.springframework.cache.annotation.EnableCaching; /** *@Author一一哥Sun *@DateCreatedin2020/4/14 *@DescriptionDescription *EnableCaching启用缓存 */ @Configuration @EnableCaching publicclassCacheConfig{ }
5.创建User实体类
packagecom.yyg.boot.domain; importlombok.Data; importlombok.ToString; importjavax.persistence.*; importjava.io.Serializable; @Entity @Table(name="user") @Data @ToString publicclassUserimplementsSerializable{ //IllegalArgumentException:DefaultSerializerrequiresaSerializablepayload //butreceivedanobjectoftype[com.syc.redis.domain.User] @Id @GeneratedValue(strategy=GenerationType.AUTO) privateLongid; @Column privateStringusername; @Column privateStringpassword; }
6.创建User仓库类
packagecom.yyg.boot.repository; importcom.yyg.boot.domain.User; importorg.springframework.data.jpa.repository.JpaRepository; publicinterfaceUserRepositoryextendsJpaRepository{ }
7.创建Service服务类
定义UserService接口
packagecom.yyg.boot.service; importcom.yyg.boot.domain.User; publicinterfaceUserService{ UserfindById(Longid); Usersave(Useruser); voiddeleteById(Longid); }
实现UserServiceImpl类
packagecom.yyg.boot.service.impl; importcom.yyg.boot.domain.User; importcom.yyg.boot.repository.UserRepository; importcom.yyg.boot.service.UserService; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.cache.annotation.CacheEvict; importorg.springframework.cache.annotation.CachePut; importorg.springframework.cache.annotation.Cacheable; importorg.springframework.stereotype.Service; @Service publicclassUserServiceImplimplementsUserService{ @Autowired privateUserRepositoryuserRepository; //普通的缓存+数据库查询代码实现逻辑: //Useruser=RedisUtil.get(key); //if(user==null){ //user=userDao.findById(id); ////redis的key="product_item_"+id //RedisUtil.set(key,user); //} //returnuser; /** *注解@Cacheable:查询的时候才使用该注解! *注意:在Cacheable注解中支持EL表达式 *redis缓存的key=user_1/2/3.... *redis的缓存雪崩,缓存穿透,缓存预热,缓存更新... *condition="#resultnenull",条件表达式,当满足某个条件的时候才进行缓存 *unless="#resulteqnull":当user对象为空的时候,不进行缓存 */ @Cacheable(value="user",key="#id",unless="#resulteqnull") @Override publicUserfindById(Longid){ returnuserRepository.findById(id).orElse(null); } /** *注解@CachePut:一般用在添加和修改方法中 *既往数据库中添加一个新的对象,于此同时也往redis缓存中添加一个对应的缓存. *这样可以达到缓存预热的目的. */ @CachePut(value="user",key="#result.id",unless="#resulteqnull") @Override publicUsersave(Useruser){ returnuserRepository.save(user); } /** *CacheEvict:一般用在删除方法中 */ @CacheEvict(value="user",key="#id") @Override publicvoiddeleteById(Longid){ userRepository.deleteById(id); } }
8.创建Controller接口方法
packagecom.yyg.boot.web; importcom.yyg.boot.domain.User; importcom.yyg.boot.service.UserService; importlombok.extern.slf4j.Slf4j; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.http.HttpStatus; importorg.springframework.http.ResponseEntity; importorg.springframework.web.bind.annotation.*; @RestController @RequestMapping("/user") @Slf4j publicclassUserController{ @Autowired privateUserServiceuserService; @PostMapping publicUsersaveUser(@RequestBodyUseruser){ returnuserService.save(user); } @GetMapping("/{id}") publicResponseEntitygetUserById(@PathVariable("id")Longid){ Useruser=userService.findById(id); log.warn("user="+user.hashCode()); HttpStatusstatus=user==null?HttpStatus.NOT_FOUND:HttpStatus.OK; returnnewResponseEntity<>(user,status); } @DeleteMapping("/{id}") publicStringremoveUser(@PathVariable("id")Longid){ userService.deleteById(id); return"ok"; } }
9.创建入口类
packagecom.yyg.boot; importorg.springframework.boot.SpringApplication; importorg.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication publicclassCacheApplication{ publicstaticvoidmain(String[]args){ SpringApplication.run(CacheApplication.class,args); } }
10.完整项目结构
11.启动项目进行测试
我们首先调用添加接口,往数据库中添加一条数据。
可以看到数据库中,已经成功的添加了一条数据。
然后测试一下查询接口方法。
此时控制台打印的User对象的hashCode如下:
我们再多次执行查询接口,发现User对象的hashCode值不变,说明数据都是来自于缓存,而不是每次都重新查询。
至此,我们就实现了SpringBoot中默认的缓存方案。
总结
到此这篇关于SpringBoot中默认缓存实现方案的示例代码的文章就介绍到这了,更多相关SpringBoot默认缓存内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。