美文网首页
SpringBoot2.0配置整合Redis

SpringBoot2.0配置整合Redis

作者: 菜菜少吃菜 | 来源:发表于2018-09-09 01:51 被阅读0次

Letture

SpringBoot2.0以前移植使用jedis作为客户端,2.0之后改采用Lettuce,主要还是为了弥补jedis的不足,jedis是直接连接Redis Server,除非使用线程池强行增加物理连接,否则在多线程下是不安全的,而Lettuce专为多线程环境下设计,且线程安全,同时支持按需增加连接。

Redis配置

  • 导入依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
  • 配置
spring:
  redis:
    host: 127.0.0.1
    port: 6379
    password:
    timeout: 3600ms #超时时间
    lettuce:
      pool:
        max-active: 8 #最大连接数
        max-idle: 8 #最大空闲连接 默认8
        max-wait: -1ms #默认-1 最大连接阻塞等待时间
        min-idle: 0 #最小空闲连接
  • 序列化Template
/**
 * Redis缓存配置类
 * @author xc
 *
 */
@Configuration
@EnableCaching
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig extends CachingConfigurerSupport {
    public RedisConfig() {
        System.out.println("RedisConfig容器启动初始化。。。");
    }
    @Resource
    private LettuceConnectionFactory lettuceConnectionFactory;

    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuffer sb = new StringBuffer();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }


    // 缓存管理器
    @Bean
    public CacheManager cacheManager() {
        RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder
                .fromConnectionFactory(lettuceConnectionFactory);
        @SuppressWarnings("serial")
        Set<String> cacheNames = new HashSet<String>() {
            {
                add("codeNameCache");
            }
        };
        builder.initialCacheNames(cacheNames);
        return builder.build();
    }
    @Bean
    public RedisTemplate<String,Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory){
        RedisTemplate<String,Serializable> template = new RedisTemplate<String,Serializable>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());// Hash key序列化
    template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());// Hash value序列化
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}
  • 使用
    @Autowired
    private RedisTemplate redisCacheTemplate;
    @RequestMapping("/setString")
    public String setString(String key, String value){
        User user = new User();
        user.setName("xc");
        redisCacheTemplate.opsForValue().set("qwe", user);
        User map2 = (User) redisCacheTemplate.opsForValue().get("qwe");
        System.out.println(map2.getName());
        return "done";
    }

可以在rdm中看到结果


image.png

注意点:
1. @Bean注入的对象默认为方法名,所以@Autowired导入也应该是方法名
2. @Autowired默认按类型查找对象,@Resource默认按name查找
3. 如果启动类不和配置类(加了@Configuration)的包在同一级目录会报错,需要在启动加注解@ComponentScan(value{"com.springboot.controller","com.springboot.config"}),controller同理。

相关文章

网友评论

      本文标题:SpringBoot2.0配置整合Redis

      本文链接:https://www.haomeiwen.com/subject/xanlgftx.html