使用 SpringBoot 之 JPA 整合 Redis 实现缓存
发布日期:2021-06-30 16:50:44
浏览次数:3
分类:技术文章
本文共 5925 字,大约阅读时间需要 19 分钟。
一、前言
数据库中的 select 是使用最频繁的,而且每次基本都是一样的,而 update、delete、insert 使用的频率没有 select 高,并且每次基本都是不一样的。为了减少数据库的压力,有必要对 select 使用缓存。
以前使用的是 Ehcache 做缓存,但是其有很明显的缺点:- 没有 ip、port,而是使用路径的,不容易起到共享缓存的作用。
- 不支持分布式。
二、代码
github 下载本案例代码:
1、entity
package com.cun.entity;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.Table;/** * 用户实体 * @author linhongcun * */@Entity@Table(name = "user")public class User{ @Id @GeneratedValue private Integer id; @Column(length = 20) private String userName; @Column(length = 20) private String password; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; }}
2、dao 接口
package com.cun.dao;import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.data.jpa.repository.JpaSpecificationExecutor;import com.cun.entity.User;/** * 用户 dao 接口 * @author linhongcun * */public interface UserDao extends JpaRepository,JpaSpecificationExecutor { }
3、Service 接口
package com.cun.service;import java.util.List;import com.cun.entity.User;public interface UserService { /** * 获取所有用户 * @return */ ListgetAllUsers();}
4、Service 实现类
package com.cun.service.impl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.cache.annotation.CacheConfig;import org.springframework.cache.annotation.Cacheable;import org.springframework.stereotype.Service;import com.cun.dao.UserDao;import com.cun.entity.User;import com.cun.service.UserService;@Service@CacheConfig(cacheNames = "userService")public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; /** * 2、在 Service 层的实现类中的方法@缓存 * ① 指定缓存的 key,为 wiselyKeyGenerator 的 bean * */ @Override @Cacheable(value = "getAllUsers",keyGenerator="wiselyKeyGenerator") public ListgetAllUsers() { return userDao.findAll(); }}
5、Controller
package com.cun.controller;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import com.cun.entity.User;import com.cun.service.UserService;@RestControllerpublic class UserController { @Autowired private UserService userService; @GetMapping("/all") public ListgetAllUsers() { System.out.println("只有第一次才会打印sql语句"); return userService.getAllUsers(); }}
6、Redis 配置
package com.cun.conf;import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;import org.springframework.cache.CacheManager;import org.springframework.cache.annotation.CachingConfigurerSupport;import org.springframework.cache.annotation.EnableCaching;import org.springframework.cache.interceptor.KeyGenerator;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.cache.RedisCacheManager;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import java.lang.reflect.Method;/** * Redis 缓存配置类(通用) * @author linhongcun * */@Configuration@EnableCachingpublic class RedisConfig extends CachingConfigurerSupport { /** * 缓存对象集合中,缓存是以 key-value 形式保存的。当不指定缓存的 key 时,SpringBoot 会使用 SimpleKeyGenerator 生成 key。 * @return */ @Bean public KeyGenerator wiselyKeyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); } }; } @Bean public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) { return new RedisCacheManager(redisTemplate); } @Bean public RedisTemplateredisTemplate(RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); @SuppressWarnings({ "rawtypes", "unchecked" }) Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; }}
7、application.yml
server: port: 80 context-path: /spring: redis: host: 120.79.197.130 port: 6378 datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/mybatis username: root password: 123 jpa: hibernate: ddl-auto: update show-sql: true
8、Redis-SpringBoot 的 pom.xml
三、测试
1、原Redis数据库,空空如也
2、第一次执行查询
①浏览器
②控制台
③Redis 数据库
2、第二次查询
①控制台
四、小结、注意
1、缓存注解是在 service 层
,而不是在 Controller 层!!!
转载地址:https://larger5.blog.csdn.net/article/details/79696562 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
做的很好,不错不错
[***.243.131.199]2024年04月16日 18时42分19秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
LVM逻辑卷------基础命令详解(三分钟入门)
2019-04-30
LVM逻辑卷------详细操作过程(三分钟上手)
2019-04-30
mysql——介绍及安装与基本用法
2019-04-30
MySQL数据库之索引
2019-04-30
MYSQL——事务操作+视图+存储引擎
2019-04-30
Mysql——完全备份+增量备份+备份恢复
2019-04-30
MySQL进阶查询(SELECT 语句高级用法)
2019-04-30
Mysql 之主从复制
2019-04-30
LVS负载均衡------NAT模式
2019-04-30
squid代理-----透明代理模式
2019-04-30
squid代理介绍----ACL控制应用+sarg日志分析+反向代理
2019-04-30
redis集群之主从模式+哨兵模式
2019-04-30
JavaScript原生开关灯效果
2019-04-30
企业邮箱如何申请注册,邮箱申请如何免费注册?
2019-04-30
微信企业邮箱,手机邮箱格式地址怎么写?
2019-04-30
公司如何申请企业邮箱,公司邮箱怎么申请,公司企业邮箱哪个好?
2019-04-30
电子邮箱账号怎么申请,怎样申请邮箱账号呢
2019-04-30
邮箱怎么发邮件,邮件发信量多少,职场新人怎么发汇报邮件呢?
2019-04-30