Spring Boot系列(七)Spring Boot使用Redis實現session共用

來源:互聯網
上載者:User
            Spring Boot系列(七)Spring Boot使用Redis實現session共用

這一篇介紹Spring Boot使用Redis實現session共用,需要springboot實戰完整視頻教程的,點擊這裡。


Redis是一個緩衝訊息中介軟體及具有豐富特性的KVStore for Redis系統。Spring Boot為Jedis用戶端庫和由Spring Data Redis提供的基於Jedis用戶端的抽象提供自動設定。spring-boot-starter-redis'Starter POM'為收集依賴提供一種便利的方式。


引入spring-boot-starter-redis,在pom.xml設定檔中增加配置如下(基於之前章節“Spring Boot 構建架構”中的pom.xml檔案):


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


可以注入一個自動設定的RedisConnectionFactory,StringRedisTemplate或普通的跟其他Spring Bean相同的RedisTemplate執行個體。預設情況下,這個執行個體將嘗試使用localhost:6379串連Redis伺服器。


@Component
public class MyBean {
   private StringRedisTemplate template;
   
   @Autowired
   public MyBean(StringRedisTemplate template) {
       this.template = template;
   }
   // ...
}


如果添加一個自己的任何自動設定類型的@Bean,它將替換預設的(除了RedisTemplate的情況,它是根據bean的名稱'redisTemplate'而不是它的類型進行排除的)。如果在classpath路徑下存在commons-pool2,預設會獲得一個串連池工廠。


應用使用Redis案例


添加設定檔,配置內容如下:


# REDIS (RedisProperties)
# Redis伺服器位址
spring.redis.host=192.168.0.58
# Redis伺服器串連連接埠
spring.redis.port=6379  
# 連線逾時時間(毫秒)
spring.redis.timeout=0


redis配置類,具體代碼如下:


import org.springframework.boot.context.properties.ConfigurationProperties;  
import org.springframework.stereotype.Component;  
 
@Component  
@ConfigurationProperties(prefix = "spring.redis")  
public class RedisConn {  
     
   private String host;  
     
   private int port;  
     
   private int timeout;  
 
 
   public String getHost() {  
       return host;  
   }  
 
   public void setHost(String host) {  
       this.host = host;  
   }  
 
   public int getPort() {  
       return port;  
   }  
 
   public void setPort(int port) {  
       this.port = port;  
   }  
 
   public int getTimeout() {  
       return timeout;  
   }  
 
   public void setTimeout(int timeout) {  
       this.timeout = timeout;  
   }  
 
   @Override  
   public String toString() {  
       return "Redis [localhost=" + host + ", port=" + port + ", timeout=" + timeout + "]";  
   }  
     
 
}


注意:在RedisConn類中註解@ConfigurationProperties(prefix = "spring.Redis")的作用是讀取springboot的預設設定檔資訊中以spring.redis開頭的資訊。


配置cache類


import java.lang.reflect.Method;  
import java.util.HashMap;  
import java.util.Map;  

import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.beans.factory.annotation.Value;  
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.ComponentScan;  
import org.springframework.context.annotation.Configuration;  
import org.springframework.context.annotation.PropertySource;  
import org.springframework.data.redis.cache.RedisCacheManager;  
import org.springframework.data.redis.connection.RedisConnectionFactory;  
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;  
import org.springframework.data.redis.core.RedisTemplate;  
import org.springframework.data.redis.core.StringRedisTemplate;  
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;  
import org.springframework.stereotype.Component;  

import com.cachemodle.RedisConn;  
import com.fasterxml.jackson.annotation.JsonAutoDetect;  
import com.fasterxml.jackson.annotation.PropertyAccessor;  
import com.fasterxml.jackson.databind.ObjectMapper;  

/**
*  
* @author sandsa redis cache service
*
*/  

@Configuration  
@EnableCaching  
public class RedisConfig extends CachingConfigurerSupport {  

  @Autowired  
  private RedisConn redisConn;  
   
  /**
   * 生產key的策略
   *  
   * @return
   */  

  @Bean  
  @Override  
  public KeyGenerator keyGenerator() {  
      return new KeyGenerator() {  

          @Override  
          public Object generate(Object target, Method method, Object... params) {  
              StringBuilder sb = new StringBuilder();  
              sb.append(target.getClass().getName());  
              sb.append(method.getName());  
              for (Object obj : params) {  
                  sb.append(obj.toString());  
              }  
              return sb.toString();  
          }  
      };  

  }  

  /**
   * 管理緩衝
   *  
   * @param redisTemplate
   * @return
   */  

  @SuppressWarnings("rawtypes")  
  @Bean  
  public CacheManager CacheManager(RedisTemplate redisTemplate) {  
      RedisCacheManager rcm = new RedisCacheManager(redisTemplate);  
      // 設定cache到期時間,時間單位是秒  
      rcm.setDefaultExpiration(60);  
      Map<String, Long> map = new HashMap<String, Long>();  
      map.put("test", 60L);  
      rcm.setExpires(map);  
      return rcm;  
  }  
   
  /**
 
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.