一塊兒來學SpringBoot | 第九篇:整合Lettuce Redis

SpringBoot 是爲了簡化 Spring 應用的建立、運行、調試、部署等一系列問題而誕生的產物, 自動裝配的特性讓咱們能夠更好的關注業務自己而不是外部的XML配置,咱們只需遵循規範,引入相關的依賴就能夠輕易的搭建出一個 WEB 工程

Spring Boot 除了支持常見的ORM框架外,更是對經常使用的中間件提供了很是好封裝,隨着Spring Boot2.x的到來,支持的組件愈來愈豐富,也愈來愈成熟,其中對Redis的支持不單單是豐富了它的API,更是替換掉底層Jedis的依賴,取而代之換成了Lettuce(生菜)html

<!-- more -->java

Redis介紹

Redis是一個開源的使用ANSI C語言編寫、支持網絡、可基於內存亦可持久化的日誌型、Key-Value數據庫,並提供多種語言的API。相比Memcached它支持存儲的類型相對更多字符哈希集合有序集合列表GEO同時Redis是線程安全的。2010年3月15日起,Redis的開發工做由VMware主持,2013年5月開始,Redis的開發由Pivotal贊助。git

Lettuce

LettuceJedis 的都是鏈接Redis Server的客戶端程序。Jedis實現上是直連redis server,多線程環境下非線程安全,除非使用鏈接池,爲每一個Jedis實例增長物理鏈接Lettuce基於Netty的鏈接實例(StatefulRedisConnection),能夠在多個線程間併發訪問,且線程安全,知足多線程環境下的併發訪問,同時它是可伸縮的設計,一個鏈接實例不夠的狀況也能夠按需增長鏈接實例github

導入依賴

pom.xmlspring-boot-starter-data-redis的依賴,Spring Boot2.x 後底層不在是Jedis若是作版本升級的朋友須要注意下web

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

屬性配置

application.properties 文件中配置以下內容,因爲Spring Boot2.x 的改動,鏈接池相關配置須要經過spring.redis.lettuce.pool 或者 spring.redis.jedis.pool 進行配置了redis

spring.redis.host=localhost
spring.redis.password=battcn
# 鏈接超時時間(毫秒)
spring.redis.timeout=10000
# Redis默認狀況下有16個分片,這裏配置具體使用的分片,默認是0
spring.redis.database=0
# 鏈接池最大鏈接數(使用負值表示沒有限制) 默認 8
spring.redis.lettuce.pool.max-active=8
# 鏈接池最大阻塞等待時間(使用負值表示沒有限制) 默認 -1
spring.redis.lettuce.pool.max-wait=-1
# 鏈接池中的最大空閒鏈接 默認 8
spring.redis.lettuce.pool.max-idle=8
# 鏈接池中的最小空閒鏈接 默認 0
spring.redis.lettuce.pool.min-idle=0

具體編碼

Spring BootRedis的支持已經很是完善了,良好的序列化以及豐富的API足夠應對平常開發spring

實體類

建立一個User數據庫

package com.battcn.entity;

import java.io.Serializable;

/**
 * @author Levin
 * @since 2018/5/10 0007
 */
public class User implements Serializable {

    private static final long serialVersionUID = 8655851615465363473L;
    private Long id;
    private String username;
    private String password;
    // TODO  省略get set
}

自定義Template

默認狀況下的模板只能支持RedisTemplate<String, String>,也就是隻能存入字符串,這在開發中是不友好的,因此自定義模板是頗有必要的,當自定義了模板又想使用String存儲這時候就可使用StringRedisTemplate的方式,它們並不衝突...apache

package com.battcn.config;

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.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.io.Serializable;

/**
 * TODO 修改database
 *
 * @author Levin
 * @since 2018/5/10 0022
 */
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisCacheAutoConfiguration {

    @Bean
    public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Serializable> template = new RedisTemplate<>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

測試

完成準備事項後,編寫一個junit測試類來檢驗代碼的正確性,有不少人質疑過Redis線程安全性,故下面也提供了響應的測試案例,若有疑問歡迎指正緩存

package com.battcn;

import com.battcn.entity.User;
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.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.Serializable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

/**
 * @author Levin
 * @since 2018/5/10 0010
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class Chapter8ApplicationTest {

    private static final Logger log = LoggerFactory.getLogger(Chapter8ApplicationTest.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate<String, Serializable> redisCacheTemplate;


    @Test
    public void get() {
        // TODO 測試線程安全
        ExecutorService executorService = Executors.newFixedThreadPool(1000);
        IntStream.range(0, 1000).forEach(i ->
                executorService.execute(() -> stringRedisTemplate.opsForValue().increment("kk", 1))
        );
        stringRedisTemplate.opsForValue().set("k1", "v1");
        final String k1 = stringRedisTemplate.opsForValue().get("k1");
        log.info("[字符緩存結果] - [{}]", k1);
        // TODO 如下只演示整合,具體Redis命令能夠參考官方文檔,Spring Data Redis 只是改了個名字而已,Redis支持的命令它都支持
        String key = "battcn:user:1";
        redisCacheTemplate.opsForValue().set(key, new User(1L, "u1", "pa"));
        // TODO 對應 String(字符串)
        final User user = (User) redisCacheTemplate.opsForValue().get(key);
        log.info("[對象緩存結果] - [{}]", user);
    }
}
其它類型

下列的就是Redis其它類型所對應的操做方式

  • opsForValue: 對應 String(字符串)
  • opsForZSet: 對應 ZSet(有序集合)
  • opsForHash: 對應 Hash(哈希)
  • opsForList: 對應 List(列表)
  • opsForSet: 對應 Set(集合)
  • opsForGeo: 對應 GEO(地理位置)

總結

spring-data-redis文檔: https://docs.spring.io/spring-data/redis/docs/2.0.1.RELEASE/reference/html/#new-in-2.0.0
Redis 文檔: https://redis.io/documentation
Redis 中文文檔: http://www.redis.cn/commands.html

目前不少大佬都寫過關於 SpringBoot 的教程了,若有雷同,請多多包涵,本教程基於最新的 spring-boot-starter-parent:2.0.1.RELEASE編寫,包括新版本的特性都會一塊兒介紹...

說點什麼

  • 我的QQ:1837307557
  • battcn開源羣(適合新手):391619659
  • 微信公衆號(歡迎調戲):battcn

公衆號

我的博客:http://blog.battcn.com/

全文代碼:https://github.com/battcn/spring-boot2-learning/tree/master/chapter8

相關文章
相關標籤/搜索