欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot2.x整合redis

程序员文章站 2022-07-07 11:52:18
...

  写这篇博客的主要原因是之前用s之前用springboot1.x使用redis是OK的,因为1.x默认使用jedis客户端。而到了2.0就成了lettuce。Jedis和lettuce都是连接的redis server服务,区别是前者线程不安全,除非配置线程池,为每个线程实现一个物理连接。而lettuce是基于netty。线程安全的。接下来就是整合。 

    1.导包

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
	<version>2.6.2</version>
</dependency>

2.配置文件

#redis
# 连接设置
spring.redis.database=2
spring.redis.host=192.168.94.8
spring.redis.port=6379
#spring.redis.password=123456
#spring.redis.timeout=10000ms
# 连接池设置
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.max-wait=
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.pool.max-active=8

3.创建配置类

package com.af.config;

import lombok.extern.slf4j.Slf4j;
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.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;


/**
 * @Author AF
 * @Description
 * @Date 2019/12/12 0:00
 */
@Configuration
@Slf4j
public class RedisConfig {
//lettuce客户端连接工厂
    @Resource
    private LettuceConnectionFactory lettuceConnectionFactory;
    //日志;
    // json序列化器
    private Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    //缓存生存时间
    private Duration timeToLive = Duration.ofDays(1);

    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        //redis缓存配置
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(this.timeToLive)
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))
                .disableCachingNullValues();
         //缓存配置map
        Map<String,RedisCacheConfiguration> cacheConfigurationMap=new HashMap<>();
          //自定义缓存名,后面使用的@Cacheable的CacheName
        cacheConfigurationMap.put("users",config);
        cacheConfigurationMap.put("default",config);
        //根据redis缓存配置和reid连接工厂生成redis缓存管理器
        RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(config)
                .transactionAware()
                .withInitialCacheConfigurations(cacheConfigurationMap)
                .build();
        log.debug("自定义RedisCacheManager加载完成");
        return redisCacheManager;
    }

    //redisTemplate模板提供给其他类对redis数据库进行操作
    @Bean(name = "redisTemplate")
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(keySerializer());
        redisTemplate.setHashKeySerializer(keySerializer());
        redisTemplate.setValueSerializer(valueSerializer());
        redisTemplate.setHashValueSerializer(valueSerializer());
/*
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));
        redisTemplate.setConnectionFactory(redisConnectionFactory);*/
        log.debug("自定义RedisTemplate加载完成");
        return redisTemplate;
    }

    //redis键序列化使用StrngRedisSerializer
    private RedisSerializer<String> keySerializer() {
        return new StringRedisSerializer();
    }

    //redis值序列化使用json序列化器
    private RedisSerializer<Object> valueSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }


    //缓存键自动生成器
    @Bean
    public KeyGenerator myKeyGenerator() {
        return (target, method, 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();
        };
    }
}

4.编码

       1)注入

 @Autowired
 private RedisTemplate  redisTemplate;

      2)设置以及获取值,这里使用的是RedisTemlete,它有几个如下方法

            常用:

                opsForValue :对应 String(字符串)
                opsForZSet:对应 ZSet(有序集合)
                opsForHash:对应 Hash(哈希)
                opsForList:对应 List(列表)
                opsForSet:对应 Set(集合)
                opsForGeo:对应 GEO(地理位置)

     

redisTemplate.opsForValue().set(CODE_KEY+":"+ownerId,kaptchaText,60, TimeUnit.SECONDS);

       设置值无法就是常用的key-value,但是有一个要注意,如果使用的是opsForValue去set,后面一定要加      TimeUnit.SECONDS,不然存入的值都会变成\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00。

      

相关标签: 整合&异常