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

直接貼代碼:

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配置相對簡單,實際的項目開發中,我們合理的去使用,讓我們開發的代碼更好一些,少讓別人說我們寫的代碼有各種問題,提高自我的這種意識。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章