使用 SpringBoot 之 JPA 整合 Redis 实现缓存
发布日期:2021-06-30 16:50:44 浏览次数:4 分类:技术文章

本文共 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 */ List
getAllUsers();}

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 List
getAllUsers() { 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 List
getAllUsers() { 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 RedisTemplate
redisTemplate(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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:SpringBoot 结合 JSR303 对前端数据进行校验
下一篇:[Java爬虫] 使用 HtmlUnit + Xpath 模拟点击、动态获取信息

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年05月01日 13时17分46秒