Springboot 2.X中Spring-cache与redis整合

本文转自:Springboot 2.X中Spring-cache与redis整合

Springboot 2.X中Spring-cache与redis整合

Springboot中Spring-cache与redis整合。这也是一个不错的框架,与spring的事务使用类似,只要添加一些注解方法,就可以动态的去操作缓存了,减少代码的操作。如果这些注解不满足项目的需求,我们也可以参考spring-cache的实现思想,使用AOP代理+缓存操作来管理缓存的使用。

在这个例子中我使用的是redis,当然,因为spring-cache的存在,我们可以整合多样的缓存技术,例如Ecache、Mamercache等。

1. 在pom.xml中添加以下依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

注意:spring-boot-starter-web默认引入了以下jackson相关的依赖:

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.8.0</version>
</dependency>
<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.8.7</version>
</dependency>
<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.7</version>
</dependency>

2. redis客户端配置

无论使用spring-boot的哪个版本,我们都需要先配置redis连接,两个版本的redis客户端连接池使用有所不同。

spring-boot版本默认客户端类型
1.5.xjedis
2.xlettuce

在1.5.x中,我们配置jedis连接池只需要配置 spring.redis.pool.* 开始的配置即可,如下配置

spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.min-idle=0
spring.redis.pool.max-idle=8

但在2.x版本中由于引入了不同的客户端,需要指定配置哪种连接池,如下配置

在application.properties中添加如下代码:

# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379  
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接超时时间(毫秒)
spring.redis.timeout=500ms

# 设置缓存默认超过期时间为30秒  
spring.cache.redis.time-to-live.seconds=10

#jedis
# 连接池最大连接数(使用负值表示没有限制)
#spring.redis.jedis.pool.max-active=8  
# 连接池最大阻塞等待时间(使用负值表示没有限制)
#spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
#spring.redis.jedis.pool.max-idle=8  
# 连接池中的最小空闲连接
#spring.redis.jedis.pool.min-idle=0
 
#lettuce客户端   
spring.redis.lettuce.pool.min-idle=0  
spring.redis.lettuce.pool.max-idle=8  
spring.redis.lettuce.pool.max-wait=-1
spring.redis.lettuce.pool.max-active=8  
spring.redis.lettuce.shutdown-timeout=100

注:spring.redis.timeout 不要配置成0,对于 lettuce,会报这个错:io.lettuce.core.RedisCommandTimeoutException: Command timed out

3. JavaConfig方式配置

通用配置方式只能满足整个程序所有缓存都采用相同公共配置的方式,如果需要特殊处理,如我们的案列,则需要自己采用代码的方式来配置。
采用代码的方式,只要需要配置的是CacheMananger,采用Redis时具体实现我们需要使用其子类RedisCacheMananger来做配置

  • 创建redis的配置类RedisConfig.java
  • 注意一定要在类上加上以下两个注解:
  • @Configuration 可理解为用spring的时候xml里面的<beans>标签
  • @EnableCaching 注解是spring framework中的注解驱动的缓存管理功能。
package com.johnfnash.learn.redis.config;

import java.lang.reflect.Method;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
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.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

@Configuration
@EnableCaching // Enables Spring's annotation-driven cache management capability
public class RedisConfig extends CachingConfigurerSupport {
    @Value("${spring.redis.host}")
    private String hostName;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.cache.redis.time-to-live.seconds}")
    private int entryTTL;

    @Bean
    public LettuceConnectionFactory redisConnectionFactory() {
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(hostName, port);
        return new LettuceConnectionFactory(config);
    }

    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            // 当没有指定缓存的 key时来根据类名、方法名和方法参数来生成key
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append('.').append(method.getName());
                if(params.length > 0) {
                    sb.append('[');
                    for (Object obj : params) {
                        sb.append(obj.toString());
                    }
                    sb.append(']');
                }
                System.out.println("keyGenerator=" + sb.toString());
                return sb.toString();
            }
        };
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        return new RedisCacheManager(
                 RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory),
                 this.getRedisCacheConfigurationWithTtl(entryTTL),  // 默认策略,未配置的 key 会使用这个
                 this.getRedisCacheConfigurationMap()               // 指定 key 策略
            );
    }

    private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
        Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<String, RedisCacheConfiguration>();
        redisCacheConfigurationMap.put("user", this.getRedisCacheConfigurationWithTtl(30)); // 单独设置某些cache的超时时间
        return redisCacheConfigurationMap;
    }

    private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
        // 设置CacheManager的值序列化方式为JdkSerializationRedisSerializer,
        // 但其实RedisCacheConfiguration默认就是使用StringRedisSerializer序列化key,
        // JdkSerializationRedisSerializer序列化value,所以以下注释代码为默认实现
        // ClassLoader loader = this.getClass().getClassLoader();
        // JdkSerializationRedisSerializer jdkSerializer = new
        // JdkSerializationRedisSerializer(loader);
        // RedisSerializationContext.SerializationPair<Object> pair =
        // RedisSerializationContext.SerializationPair.fromSerializer(jdkSerializer);
        // RedisCacheConfiguration defaultCacheConfig =
        // RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);
        // RedisCacheConfiguration defaultCacheConfig =
        // RedisCacheConfiguration.defaultCacheConfig();

        Jackson2JsonRedisSerializer<Object> 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);

        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        redisCacheConfiguration = redisCacheConfiguration
                .serializeValuesWith(
                        RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .entryTtl(Duration.ofSeconds(seconds));

        return redisCacheConfiguration;
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);

        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
                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.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

}

以上代码中RedisCacheConfiguration类为2.x新增的配置类,增加了几个配置项。

注意,构造 CacheManager 的时候,默认使用 JdkSerializationRedisSerializer序列化value,写入 redis 中的value大致如下:

\xac\xed\x00\x05sr\x00\x1fcom.johnfnash.redis.domain.User9\x8d$\x90\x0e\x8f\x1cb\x02\x00\x03L\x00\x02idt\x00\x10Ljava/lang/Long;L\x00\x04namet\x00\x12Ljava/lang/String;L\x00\bpasswordq\x00~\x00\x02xpsr\x00\x0ejava.lang.Long;\x8b\xe4\x90\xcc\x8f#\xdf\x02\x00\x01J\x00\x05valuexr\x00\x10java.lang.Number\x86\xac\x95\x1d\x0b\x94\xe0\x8b\x02\x00\x00xp\x00\x00\x00\x00\x00\x00\x00\x03t\x00\x041111t\x00\b11223434

要想直观的看到各个属性的情况,可以使用 Jackson2JsonRedisSerializer 序列化 value。改用 Jackson 序列化后的value大致为如下形式:

"[\"java.util.Arrays$ArrayList\",[[\"com.johnfnash.redis.domain.User\",{\"id\":1,\"name\":\"1111\",\"password\":\"11223434\"}],[\"com.johnfnash.redis.domain.User\",{\"id\":2,\"name\":\"1111\",\"password\":\"11223434\"}],[\"com.johnfnash.redis.domain.User\",{\"id\":3,\"name\":\"1111\",\"password\":\"11223434\"}]]]"

另外,注意其中缓存的生效时间的设置(这一部分可以参考:SpringBoot 2.X @Cacheable,redis-cache 如何根据key设置缓存时间?)。

到这里基本的配置就已经完成了

4. 实例

4.1 实体类 User.java

import java.io.Serializable;

public class User implements Serializable {

	private static final long serialVersionUID = 4147011033016245346L;

	private Long id;
	private String name;
	private String password;

	// setter, getter

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", password=" + password + "]";
	}
	
}

4.2 业务层

接口 UserService.java

import java.util.List;

import com.johnfnash.redis.domain.Info;
import com.johnfnash.redis.domain.User;

public interface UserService {

	List<User> list();  
	  
    User findUserById(Long id);  
  
    Info findInfoById(Long id);  
  
    void update(User user);  
  
    void remove(Long id);  
  
    User upuser(Long id);  
    
    User saveUser(User user);
	
}

实现类

package com.johnfnash.learn.redis.service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.johnfnash.learn.redis.entity.User;

@Service
@CacheConfig(cacheNames = "user") //指定cache的名字,这里指定了 caheNames,下面的方法的注解里就可以不用指定 value 属性了
public class UserServiceImpl implements UserService {

    private Map<Long, User> userMap = new HashMap<Long, User>();  
    
    public UserServiceImpl() {  
        User u1=new User();  
        u1.setId(1L);  
        u1.setName("1111");  
        u1.setPassword("11223434");  
        User u2=new User();  
        u2.setId(2L);  
        u2.setName("1111");  
        u2.setPassword("11223434");  
        User u3=new User();  
        u3.setId(3L);  
        u3.setName("1111");  
        u3.setPassword("11223434");  
          
        userMap.put(1L,u1);  
        userMap.put(2L,u2);  
        userMap.put(3L,u3);  
    }
    
    @Cacheable()
    @Override
    public List<User> list() {
        System.out.println("querying list.....");
        User[] users = new User[userMap.size()];
        this.userMap.values().toArray(users);
        return Arrays.asList(users);
    }

    @Cacheable(key = "'user:'.concat(#id.toString())")
    @Override
    public User findUserById(Long id) {
        System.out.println("find user by id...");
        return userMap.get(id);
    }

    @Cacheable(key = "'user:'.concat(#user.id)")
    @Override
    public void update(User user) {
        System.out.println("update user and cache...");
        userMap.put(user.getId(), user);
    }

    // 清空cache
    @CacheEvict(key = "'user:'.concat(#id.toString())")
    @Override
    public void remove(Long id) {
        System.out.println("remove user...");
        userMap.remove(id);
    }

    @CacheEvict(key = "'user:'.concat(#id.toString())")
    @Override
    public User upuser(Long id) {
        System.out.println("update user and remove cache...");
        User d = userMap.get(id);
        d.setName("0000000000000000000000000000000000000000");
        return d;
    }

    @CachePut(key = "'user:'.concat(#user.id)")
    @Override
    public User saveUser(User user) {
        System.out.println("each time add/update user and update cache...");
        userMap.put(user.getId(), user);
        return user;
    }

}

需要注意的是 @CacheEvict、@CachePut、@Cacheable 这三种注解用法的区分与不同,下面将对 service 层这几个方法进行测试(也可以参考:注释驱动的 Spring cache 缓存介绍)。

Service 层测试

package com.johnfnash.learn;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.johnfnash.learn.redis.entity.User;
import com.johnfnash.learn.redis.service.UserService;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringCacheRedisApplicationTests {
    private static final long USER_ID_TO_TEST = 1L;
    
    @Autowired
    private UserService userService;
    
    @Test
    public void testList() {
        System.out.println("first query...");
        System.out.println(userService.list());
        System.out.println("second query...");
        System.out.println(userService.list());
    }
    
    @Test
    public void testFindById() {
        System.out.println("first query...");
        System.out.println(userService.findUserById(USER_ID_TO_TEST));
        System.out.println("second query...");
        System.out.println(userService.findUserById(USER_ID_TO_TEST));
    }
    
    @Test
    public void testUpUser() {
        System.out.println(userService.upuser(USER_ID_TO_TEST));
        testFindById();
    }
    
    @Test
    public void update() {
        User user = userService.findUserById(USER_ID_TO_TEST);
        user.setName("test name...");
        userService.update(user);
        
        user = userService.findUserById(USER_ID_TO_TEST);
        System.out.println(user);
    }

}

有兴趣的话,可以去执行每个方法,并查看输出结果,来更加深刻地认识这几个注解用法的区分。这里就不再详述了。

另外,可以通过 restful 接口来更加灵活的测试 redis 缓存。接下来的 Controller 部分将会介绍这个。

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.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class IndexController {

	@Autowired  
    private UserService userService;  
	
	@GetMapping("/users")
	public List<User> users() {
		return userService.list();
	}
	
	@GetMapping("/user/{id}")
	public User findUserById(@PathVariable("id") Long id) {
		User user = userService.findUserById(id);
		return user;
	}
	
	@PutMapping("/upuser/{id}")
    public User upuser(@PathVariable("id") Long id) {  
        return userService.upuser(id);  
    }  
  
    @PutMapping("/user/{id}/{name}")  
    public User update(@PathVariable("id") Long id, @PathVariable("name") String name) {  
        User user = userService.findUserById(id);  
        user.setName(name);  
        userService.update(user);  
        return userService.findUserById(id);  
    }  
    
}

服务启动之后,访问相应接口,查看 redis 中的相应的值

注意:不要添加热部署,否则可能会 java.lang.ClassCastException: com.whb.book.entity.Book cannot be cast to com.whb.book.entity.Book 之类的奇怪错误 (参考:springboot集成redis,使用@Cacheable导致java.lang.ClassCastException:异常

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值