Spring系列之Redis的兩種集成方式

在工作中,我們用到分散式快取的時候,第一選擇就是Redis,今天介紹一下SpringBoot如何集成Redis的,分別使用Jedis和Spring-data-redis兩種方式。

一、使用Jedis方式集成

1、增加依賴

<!-- spring-boot-starter-web不是必須的,這裡是為了測試-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
	<optional>true</optional>
</dependency>
<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
</dependency>
<dependency>
<!-- fastjson不是必須的,這裡是為了測試-->
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.73</version>
</dependency>

2、配置項

redis.host=localhost
redis.maxTotal=5
redis.maxIdle=5
redis.testOnBorrow=true
#以下方式也可以,SpringBoot同樣能將其解析注入到JedisPoolConfig中
#redis.max-total=3
#redis.max-idle=3
#redis.test-on-borrow=true

3、配置連接池

/**
 * @author 公-眾-號:程式設計師阿牛
 * 由於Jedis實例本身不非執行緒安全的,因此我們用JedisPool
 */
@Configuration
public class CommonConfig {
    @Bean
    @ConfigurationProperties("redis")
    public JedisPoolConfig jedisPoolConfig() {
        return new JedisPoolConfig();
    }

    @Bean(destroyMethod = "close")
    public JedisPool jedisPool(@Value("${redis.host}") String host) {
        return new JedisPool(jedisPoolConfig(), host);
    }
}

4、測試

/**
 * @author 公-眾-號:程式設計師阿牛
 */
@RestController
public class JedisController {
    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("getUser")
    public String getUserFromRedis(){
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId("A0001");
        userInfo.setUserName("張三丰");
        userInfo.setAddress("武當山");
        jedisPool.getResource().set("userInfo", JSON.toJSONString(userInfo));
        UserInfo userInfo1 = JSON.parseObject(jedisPool.getResource().get("userInfo"),UserInfo.class);
        return userInfo1.toString();
    }
}

運行結果如下:
file
我們可以自己包裝一個RedisClient,來簡化我們的操作

使用spring-data-redis

1、引入依賴

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

2、配置項

在application.properties中增加配置

spring.redis.host=localhost
spring.redis.port=6379

3、使用

/**
 * @author 公-眾-號:程式設計師阿牛
 */
@RestController
public class RedisController {
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("getUser2")
    public String getUserFromRedis(){
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId("A0001");
        userInfo.setUserName("張三丰");
        userInfo.setAddress("武當山");
        redisTemplate.opsForValue().set("userInfo", userInfo);
        UserInfo userInfo1 = (UserInfo) redisTemplate.opsForValue().get("userInfo");
        return userInfo1.toString();
    }
}

是的,你只需要引入依賴、加入配置就可以使用Redis了,不要高興的太早,這裡面會有一些坑

4、可能會遇到的坑

file
使用工具查看我們剛才set的內容,發現key前面多了一串字元,value也是不可見的

原因

使用springdataredis,默認情況下是使用org.springframework.data.redis.serializer.JdkSerializationRedisSerializer這個類來做序列化
具體我們看一下RedisTemplate 程式碼如何實現的

/**
*在初始化的時候,默認的序列化類是JdkSerializationRedisSerializer
*/
public void afterPropertiesSet() {
        super.afterPropertiesSet();
        boolean defaultUsed = false;
        if (this.defaultSerializer == null) {
            this.defaultSerializer = new JdkSerializationRedisSerializer(this.classLoader != null ? this.classLoader : this.getClass().getClassLoader());
        }
   ...省略無關程式碼
}
如何解決

很簡單,自己定義RedisTemplate並指定序列化類即可

/**
 * @author 公-眾-號:程式設計師阿牛
 */
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        template.setValueSerializer(jackson2JsonRedisSerializer());
        //使用StringRedisSerializer來序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jackson2JsonRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    public RedisSerializer<Object> jackson2JsonRedisSerializer() {
        //使用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);
        return serializer;
    }

}

查看運行結果:
file

哨兵和集群

只需要改一下配置項即可

# 哨兵
spring.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes=127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381

#集群
spring.redis.cluster.max-redirects=100
spring.redis.cluster.nodes=127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382,127.0.0.1:6383,127.0.0.1:6384

總結:

以上兩種方式都可以,但是還是建議你使用Spring-data-redis,因為Spring經過多年的發展,尤其是Springboot的日漸成熟,已經為我們簡化了很多操作。
關注我,下一篇繼續
file