Spring Cloud整合Redis

項目須要使用Redis來作緩存,研究了一下如何將其與Spring Boot整合。網上的demo要麼就是太過於龐大,要麼就是版本過於陳舊,配置時候會有各類坑。所以本身在踩過了各類坑以後,寫一個小demo來記錄下:java

1.項目結構:node

2.pom的依賴配置:redis

本人使用的Spring Boot是2.0.4.RELEASE版本的:spring

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

添加redis的依賴:apache

 

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

 

添加common-pool2的依賴:緩存

<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.0</version>
        </dependency>

 

我在這裏嘗試過不加version,讓springboot本身選擇最合適的版本,結果會報錯。參考別人的例子,選擇2.0版本,沒有問題。springboot

3.修改application.yml:app

這裏的host填寫本身redis的IP,timeout別設置爲0,不然運行會報錯spring-boot

redis 單機配置測試

spring:
  redis:
    host: 
    port: 6379
    lettuce:
      pool:
        max-wait: 100000
        max-idle: 10
        max-active: 100
    timeout: 5000

 

redis 集羣配置

redis:
    database: 0
    # 集羣設置 begin
    cluster:
      nodes:
        - 10.217.17.70:7000
        - 10.217.17.74:7000
        - 10.217.17.75:7000
      max-redirects: 3 # 獲取失敗 最大重定向次數
    #集羣設置 end
    #單節點 begin
#    host: 10.217.17.74
#    port: 7000
    #單節點 end
    lettuce:
      pool:
        max-wait: 100000
        max-idle: 10
        max-active: 100
    timeout: 5000

 

 

3.編寫dao層 :

package com.hg.redis;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;
 
import java.util.concurrent.TimeUnit;
 
/**
 * @Description:
 * @Author: jiangfan
 * @CreateTime 2018/9/27 上午10:14
 */
@Repository
public class RedisDao {
    @Autowired
    private StringRedisTemplate template;
 
    public void setKey(String key, String value) {
        ValueOperations<String, String> ops = template.opsForValue();
        ops.set(key, value);
    }
 
    public String getValue(String key) {
        ValueOperations<String, String> ops = this.template.opsForValue();
        return ops.get(key);
    }
}

 

 

4.修改測試啓動類:

package com.hg.redis;
 
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
 
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisApplicationTests {
 
	@Test
	public void contextLoads() {
	}
 
}

 

5.編寫一個測試類:

package com.hg.redis;
 
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
 
 
/**
 * @Description:
 * @Author: jiangfan
 * @CreateTime 2018/9/27 上午10:26
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootRedisApplicationTests {
    public static Logger logger = LoggerFactory.getLogger(SpringbootRedisApplicationTests.class);
 
    @Test
    public void contextLoads(){}
 
    @Autowired
    RedisDao redisDao;
 
    @Test
    public void testRedis() {
        redisDao.setKey("name","jerry");
        redisDao.setKey("age","11");
        logger.info(redisDao.getValue("name"));
        logger.info(redisDao.getValue("age"));
    }
}

 

6.運行測試類:

 

 

 

解決 key 和 value 序列號的問題

 

package com.jxlgzwh.brdp.sso.server.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
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.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig {

    /**
     * 配置自定義redisTemplate
     * @return
     */
    @Bean
    RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        //使用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);

        template.setValueSerializer(serializer);
        //使用StringRedisSerializer來序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);
        template.afterPropertiesSet();
        return template;
    }

}
相關文章
相關標籤/搜索