Spring Boot + Redis 集成

Redis

一、What is Redis ?

**Redis 是一個分佈式高性能內存(key-value)數據庫。**

二、Redis Effect ?

1.內存存儲和持久化
2.可以將熱搜關鍵字詞放入到緩存中
3.可以設定時間清除緩存
4.支持訂閱發佈消息
5.支持定時器、計數器

三、Redis main content:

1.Redis Persistence (持久化)

RDB
AOF

2.Redis Transaction(事務)

正常事務
放棄事務
全體出錯
冤頭債主
watch 監控

3.Redis Replication(主從複製)

一主二僕
薪火相傳
反客爲主
哨兵模式

四、Redis + SpringBoot 集成

1.添加 Redis 依賴 + 添加 SpringBoot 依賴 + 測試組件 + lombok插件

 <dependencies>

        <!--springboot 啓動器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>${springboot.version}</version>
        </dependency>

        <!--springboot web 啓動器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${springboot.version}</version>
        </dependency>

        <!--springboot springdata redis 啓動器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>${springboot.version}</version>
        </dependency>

        <!--springboot session redis-->
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
            <version>${springboot-session-data-redis.version}</version>
        </dependency>

        <!--springboot 測試組件-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test</artifactId>
            <version>1.4.3.RELEASE</version>
            <scope>test</scope>
        </dependency>

        <!--spring 測試組件-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>

        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
        </dependency>

        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

2.創建一個相關的Redis配置,爲了放入到spirng 容器中,名爲:RedisCacheAutoConfiguration.java

 package org.redis;
 
 import com.fasterxml.jackson.annotation.JsonAutoDetect;
 import com.fasterxml.jackson.annotation.PropertyAccessor;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import org.springframework.cache.CacheManager;
 import org.springframework.cache.annotation.CachingConfigurerSupport;
 import org.springframework.cache.annotation.EnableCaching;
 import org.springframework.cache.interceptor.KeyGenerator;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.data.redis.cache.RedisCacheManager;
 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.RedisSerializer;
 import org.springframework.data.redis.serializer.StringRedisSerializer;
 import org.springframework.scheduling.annotation.EnableScheduling;
 import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
 
 import java.lang.reflect.Method;
 
 
 /**
  * Created by Calvin on 2018/3/30
  * Redis 緩存配置類
  */
 @Configuration
 /**
  * @EnableScheduling 開啓計劃任務支持
  */
 @EnableScheduling
 /**
  * 開啓驅動緩存(啓用 spring 對註解驅動緩存的支持 )
  */
 @EnableCaching
 /**
  * @EnableRedisHttpSession 開啓redis集中式session管理,所有的session都存放到了redis中
  * @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400*30) maxInactiveIntervalInSeconds來設定session的統一過期時間
  */
 @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400*30)
 public class RedisCacheAutoConfiguration extends CachingConfigurerSupport{
 
     /**
      * 默認鍵值生成器:類名+方法名+參數
      * Cacheable中設置 key="xx"後按此生成
      * @return
      */
     @Override
     @Bean
     public KeyGenerator keyGenerator() {
         return new KeyGenerator() {
             public Object generate(Object o, Method method, Object... objects) {
                 StringBuilder sb = new StringBuilder();
                 sb.append(method.getClass().getName());
                 sb.append(method.getName());
                 for (Object obj : objects) {
                     sb.append(obj.toString());
                 }
                 return sb.toString();
             }
         };
     }
 
     //==========================================================將CacheManager 聲明爲Bean ===============================================
     /**
      * 緩存管理器
      * 作用:它是spring 緩存抽象核心,它能夠與多個流行的緩存實現進行集成
      * @param redisTemplate
      * @return
      */
     @Bean
     public CacheManager cacheManager(RedisTemplate redisTemplate){
         // 序列化String 類型的key 和 Value
         RedisSerializer redisSerializer = new StringRedisSerializer();
         //設置此模板所使用的Key序列化器
         redisTemplate.setKeySerializer(redisSerializer);
         redisTemplate.setHashKeySerializer(redisSerializer);
 
         // 將redisTemplate 放入到緩存管理器中
         RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
         // 設置緩存過期時間: 秒
         redisCacheManager.setDefaultExpiration(60*30);
         return redisCacheManager;
     }
 
 
     //==========================================================將RedisTemplate 聲明爲Bean ===============================================
     /**
      * @suppressWarnings 讓IDE 不報: Could not autowire
      * @param redisConnectionFactory
      * @return
      */
     @SuppressWarnings("SpringJavaAutowiringInspection")
     @Bean
     public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
         // Redis 數據訪問
         StringRedisTemplate redisTemplate = new StringRedisTemplate(redisConnectionFactory);
 
         StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
         // 序列化Redis的key(鍵)
         redisTemplate.setKeySerializer(stringRedisSerializer);
         Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
 
         // 使用ObjectMapper 來進行java 對象的相互轉換
         ObjectMapper om = new ObjectMapper();
         /**
          * PropertyAccessor(屬性訪問器) JsonAutoDetect(自動檢測)
          * setVisibility 設置可見性
          * om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); 設置可見性爲:所有屬性可以訪問和任何級別的字段都可以自動識別
          */
         om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
         // 啓用默認類型爲:不帶final 類型
         om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
         jackson2JsonRedisSerializer.setObjectMapper(om);
 
         // 序列化Redis的value(值)
         redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
         redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
         //afterPropertiesSet 加載配置後執行
         redisTemplate.afterPropertiesSet();
         return redisTemplate;
     }
 }

3.編寫Redis相關的接口。

    CommandsService
    AOFService
    RDBService
    RedisTransaction   
    RedisTypes

4.配置Redis相關配置在spring boot的配置下applicaiton.properties/applicaiton-dev.yml

####**application-dev.yml** spring: redis: database: 15 # Redis數據庫索引(默認爲0~15) host: 192.168.50.151 # Redis服務器地址 port: 6380 # Redis服務器連接密碼(默認爲空) pool: # 連接池 max-active: 300 # 連接池最大連接數(使用負值表示沒有限制) max-wait: 1000 # 連接池最大阻塞等待時間(使用負值表示沒有限制) max-idle: 100 # 連接池中的最大空閒連接 min-idle: 0 # 連接池中的最小空閒連接 timeout: 0 # 連接超時時間(毫秒)

####**application.properties**

   # REDIS (RedisProperties)
   # Redis數據庫索引(默認爲0)
   spring.redis.database=0  
   # Redis服務器地址
   spring.redis.host=192.168.0.58
   # Redis服務器連接端口
   spring.redis.port=6379  
   # Redis服務器連接密碼(默認爲空)
   spring.redis.password=
   # 連接池最大連接數(使用負值表示沒有限制)
   spring.redis.pool.max-active=8  
   # 連接池最大阻塞等待時間(使用負值表示沒有限制)
   spring.redis.pool.max-wait=-1  
   # 連接池中的最大空閒連接
   spring.redis.pool.max-idle=8  
   # 連接池中的最小空閒連接
   spring.redis.pool.min-idle=0  
   # 連接超時時間(毫秒)
   spring.redis.timeout=0  

5.編寫測試類

RedisConnectionTest.java

   import org.junit.Test;
   import org.junit.runner.RunWith;
   import org.redis.RedisStaterApplication;
   import org.redis.command.CommandsService;
   import org.redis.types.RedisTypes;
   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.SpringJUnit4ClassRunner;
   
   /**
    * Created by Calvin on 2018/4/2
    */
   @RunWith(SpringJUnit4ClassRunner.class)
   @SpringBootTest(classes = RedisStaterApplication.class)
   public class RedisConnectionTest {
   
       @Autowired
       private StringRedisTemplate stringRedisTemplate;
   
       @Autowired
       private RedisTemplate redisTemplate;
   
       @Autowired
       private CommandsService commandsService;
   
       @Autowired
       private RedisTypes redisTypes;
       @Test
       public void test() throws Exception{
           redisTypes.set("k2", "v2");
       }
   }

6.可以通過git clone 下載:https://git.coding.net/Calvin_1016280226/Redis.git 源代碼


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