使用 SpringBoot 之 JPA 整合 Redis 实现缓存

一、前言

数据库中的 select 是使用最频繁的,而且每次基本都是一样的,而 update、delete、insert 使用的频率没有 select 高,并且每次基本都是不一样的。为了减少数据库的压力,有必要对 select 使用缓存。
以前使用的是 Ehcache 做缓存,但是其有很明显的缺点:

  • 没有 ip、port,而是使用路径的,不容易起到共享缓存的作用。
  • 不支持分布式。

二、代码

github 下载本案例代码:https://github.com/larger5/SpringBootRedis.git
这里写图片描述

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<User, Integer>,JpaSpecificationExecutor<User>{

}
3、Service 接口
package com.cun.service;

import java.util.List;

import com.cun.entity.User;

public interface UserService {

    /**
     * 获取所有用户
     * @return
     */
    List<User> 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<User> 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;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/all")
    public List<User> 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
@EnableCaching
public 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<String, String> 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 层!!!

评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT小村

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值