【精品】Spring Boot集成Redis集群配置

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinosoft12345/article/details/87876620

直接贴代码:

1、pom.xml添加依赖配置

        <!-- 支持Redis键值存储数据库,包括spring-redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

2、application.yml添加redis集群的配置项

spring:
  redis:
    timeout: 10000 #连接超时时间(毫秒)
    cluster:
      nodes:
        - 127.0.2.39:7000
        - 127.0.2.39:7001
        - 127.0.2.39:7002
        - 127.0.2.38:7003
        - 127.0.2.38:7004
        - 127.0.2.38:7005
      max-redirects: 6
    pool:
      max-active: 8 #连接池最大连接数
      max-idle: 8 #连接池中的最大空闲连接
      min-idle: 0 #连接池中的最小空闲连接
      max-wait: -1 #连接池最大阻塞等待时间

3、程序配置RedisTemplate相关Bean对象

package com.wzz.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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 org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Author wangzz
 * @Date 2019/2/22 11:27
 * @Description
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(connectionFactory);
        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);
        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(factory);
        return stringRedisTemplate;
    }

}

4、程序调用

package com.wzz.listener;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.wzz.dao.model.TbDictionary;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author wangzz
 * @Date 2019/2/22 12:04
 * @Description
 */
@Component
@Slf4j
public class RedisCacheExecutor implements CommandLineRunner {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void run(String... args) throws Exception{

        String key = "Site_Web:Redis:key";

//        String value = String.valueOf(Calendar.getInstance().getTimeInMillis());

        TbDictionary dict = new TbDictionary();
        dict.setId(1);
        dict.setCode("XXXXXXXXXXXXXXX");

        redisTemplate.opsForValue().set(key,dict,2, TimeUnit.SECONDS);

       TbDictionary cacheDict = (TbDictionary)redisTemplate.opsForValue().get(key);

        log.info("-------------{}-----------",JSON.toJSON(cacheDict).toString());

        List<TbDictionary> list = Lists.newArrayList();
        list.add(dict);

       redisTemplate.opsForValue().set(key,list,5,TimeUnit.SECONDS);

       List<TbDictionary> cacheList = (List<TbDictionary>)redisTemplate.opsForValue().get(key);

        log.info("-------------{}-----------",JSON.toJSON(cacheList).toString());
    }
}

Redis配置相对简单,实际的项目开发中,我们合理的去使用,让我们开发的代码更好一些,少让别人说我们写的代码有各种问题,提高自我的这种意识。

猜你喜欢

转载自blog.csdn.net/sinosoft12345/article/details/87876620