ターン:https://www.cnblogs.com/mengmeng89012/p/5519698.html
今回は、セッションの共有を実現するために、Spring Boot + Redisのチュートリアルを紹介します。
Spring Bootのドキュメントで、@ EnableRedisHttpSessionを追加してSpringセッションのサポートを有効にするように指示してください。構成は次のとおりです。
- @構成
- @EnableRedisHttpSession
- パブリック クラスRedisSessionConfig {
- }
@EnableRedisHttpSessionアノテーションは、spring-session-data-redisによって提供されるため、pom.xmlファイルに追加します。
- <依存関係>
- <groupId> org.springframework.boot </ groupId>
- <artifactId> spring-boot-starter-redis </ artifactId>
- </依存関係>
- <依存関係>
- <groupId> org.springframework.session </ groupId>
- <artifactId> spring-session-data-redis </ artifactId>
- </依存関係>
次に、application.propertiesでredisサーバーの場所を設定する必要があります。ここでは、マシンを使用します。
- spring.redis.host = localhost
- spring.redis.port = 6379
このようにして、セッション共有を実現するための最も簡単なSpring Boot + Redisは、次のテストで完了します。
最初に、2つのtomcatサービスを開始します。ポートは8080と9090であり、application.properties [ダウンロードアドレス]で設定します 。
- server.port = 8080
次に、コントローラーを定義します。
- @RestController
- @RequestMapping(値= "/ admin / v1")
- パブリック クラスQuickRun {
- @RequestMapping(value = "/ first"、method = RequestMethod.GET)
- public Map <String、Object> firstResp(HttpServletRequest request){
- Map <String、Object> map = new HashMap <>();
- request.getSession()。setAttribute("request Url"、request.getRequestURL());
- map.put("リクエストURL"、request.getRequestURL());
- マップを返す;
- }
- @RequestMapping(value = "/ sessions"、method = RequestMethod.GET)
- 公開オブジェクトセッション(HttpServletRequestリクエスト){
- Map <String、Object> map = new HashMap <>();
- map.put("sessionId"、request.getSession()。getId());
- map.put("message"、request.getSession()。getAttribute("map"));
- マップを返す;
- }
- }
アクセステストの開始後、最初にTomcatポート8080にアクセスし、戻って[ダウンロードアドレス]を 取得します 。
- { 「リクエストURL」:「http:// localhost:8080 / admin / v1 / first」}
次に、ポート8080のセッションにアクセスして戻ります。
- { "sessionId":"efcc85c0-9ad2-49a6-a38f-9004403776b5"、"message":"http:// localhost:8080 / admin / v1 / first"}
最後に、ポート9090のセッションにアクセスして戻ります。
- { "sessionId":"efcc85c0-9ad2-49a6-a38f-9004403776b5"、"message":"http:// localhost:8080 / admin / v1 / first"}
2つのサーバー8080と9090から返された結果は同じで、セッションを共有していることがわかります。
この時点で最初のポート9090にアクセスする場合は、最初に以下を返します。
- { 「リクエストURL」:「http:// localhost:9090 / admin / v1 / first」}
両方のサーバーのセッションが返されます。
- { "sessionId":"efcc85c0-9ad2-49a6-a38f-9004403776b5"、"message":"http:// localhost:9090 / admin / v1 / first"}
Spring Boot + Redisを介してセッション共有を実現するのは非常に簡単であり、それも非常に便利で、負荷分散のためのnginxを使用すると、分散アプリケーションを実現できます。
-------------------------------------------------- -----
キャッシュを追加
RedisCacheConfig
パッケージcom.lzw.core.configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; インポートorg.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; / ** * 2017/6/11にZhenWeiLaiによって作成されました。 * / @Configuration @EnableCaching パブリック クラス RedisCacheConfigは 延びCachingConfigurerSupport { ロガーロガー = LoggerFactory.getLogger(RedisCacheConfig クラス)。 @値("$ {spring.redis.host}" ) プライベート文字列ホスト。 @Value( "$ {spring.redis.port}" ) private int port; @Value( "$ {spring.redis.timeout}" ) private int timeout; @Value( "$ {spring.redis.pool.max-idle}" ) private int maxIdle; @Value( "$ {spring.redis.pool.max-wait}" ) private long maxWaitMillis; @Value( "$ {spring.redis.password}" ) プライベート文字列パスワード。 JedisPool redisPoolFactory(){ logger.info( "JedisPool注入成功!!" ); JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxIdle(maxIdle); jedisPoolConfig.setMaxWaitMillis(maxWaitMillis); JedisPool jedisPool = new JedisPool(jedisPoolConfig、host、port、timeout、password); jedisPoolを返します。 } @Bean public RedisTemplate <String、String> redisTemplate(RedisConnectionFactory cf){ RedisTemplate <String、String> redisTemplate = new RedisTemplate <String、String>(); redisTemplate.setConnectionFactory(cf); return redisTemplate; } @Bean public CacheManager cacheManager(RedisTemplate redisTemplate){ RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate); // デフォルトのタイムアウト、単位秒 cacheManager.setDefaultExpiration(3000 ); // キャッシュ名に従ってタイムアウトを設定します。0はタイムアウトがないことを意味します Map <String、Long> expires = new ConcurrentHashMap <> (); cacheManager.setExpires(expires); return cacheManager; } }
application.yml
spring: datasource: #readSize:1 #name :writeDataSource type:com.alibaba.druid.pool.DruidDataSource write: driver-class-name:com.mysql.jdbc.Driver url:jdbc:mysql:// localhost:3306 / cloud?useUnicode = true &characterEncoding = UTF-8 &zeroDateTimeBehavior = convertToNull &transformedBitIsBoolean = true &useSSL = true username:root password:123 initialSize:10 maxActive:100 maxWait:60000 minIdle:5 timeBetweenEvictionRunsMillis:60000 minEvictableIdleTimeMillis:300000 validationQuery:SELECT 'x' testWhileIdle:true testOnBorrow:false testOnReturn:false poolPreparedStatements:true maxPoolPreparedStatementPerConnectionSize:20 #redis configuration redis: host:192.168.1.11 port:6379 #REDIS(RedisProperties)#Redis database index(default is 0) database:0 #Redis server connection password (デフォルトは空) password: #接続プールの最大接続数(制限がないことを示すには負の値を使用) #接続タイムアウト時間(ミリ秒) timeout:0 pool: max-active:8 #接続プールの最大ブロック待機時間(負の値を使用)制限なし) max-wait:-1 #内の最大のアイドル接続 max-idle:8 #接続プール min-idle の最小アイドル接続:0