春ブーツマルチサイト利用Redisのは、セッション共有を実現します

異なるサイト間でそれを(Webサービス・プロセスを)セッションセッションを共有する方法、原理は非常に簡単です、それは一つの場所にある、すべてのサイトがこのセッションのセッション分離ストレージこの場所から読み込まれます。

通常、我々はこの問題を解決するためのRedisを使います

  • 春のブート2.1.8
  • Redisの5.0.3

セッション共有方式

プロジェクトのgithubのソースコードのダウンロード

章は、前の記事に対処春ブーツnginxの擬似熱アップデート使用して本番環境を実現生成されたセッション共有の問題を。

1 Redisの準備

この例では、独自の検索Redisのインストール方法については、Mac用のRedis 5.0.3オペレーティング・システムを使用しています。

2春のブートテストプロジェクトを設立

2.1新しい春のブートMavenのサンプルプロジェクト

注意:IDEAはのための開発ツールです

  1. ファイル>新規>プロジェクト、以下の図を選択Spring Initializrして、[次へ]をクリックします次
  2. フィルGroupId(パッケージ名)、 Artifactプロジェクト名)にすることができます。次のクリック
    のgroupId = com.fishpro
    たartifactId = sharedsessionを
  3. 選択は異なりSpring Web Starter、フロントダニを。
  4. プロジェクト名が設定されていますspring-boot-study-sharedsession

ポンポンの導入に依存して2.2

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

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.44</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>
    </dependencies>

設定するには、2.3アプリケーション構成ファイル

server:
  port: 8084
#2.x版本中由于引入了不同客户端,需要指定配置哪种连接池
#jedis客户端
spring:
  cache:
    type: redis
  redis:
    host: 127.0.0.1
    port: 6379
    password:
    database: 0
    jedis:
      pool:
        max-active: 8
        max-wait: -1ms
        max-idle: 8
        min-idle: 0

2.4テストコードを追加します

オープンRedisSession

@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600)maxInactiveIntervalInSecondsデフォルトの時間セッションを表すアノテーションを使用して新しいクラスをRedisSessionConfig

@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600)
public class RedisSessionConfig {
}

コントローラは、ファイルを書き込むように設定してセッションを読みます

@EnableRedisHttpSession
@RestController
public class IndexController {

    @GetMapping("")
    public String index(HttpServletRequest request){
        request.getSession().setAttribute("username", "公众号 程序鱼");
        request.getSession().setMaxInactiveInterval(10*1000);
        String username = (String)request.getSession().getAttribute("username");

        return "username"+username+ " session_id:"+request.getSession().getId();
    }
}

2.5試験結果

このプロジェクトは、異なるチェック入力ポートで開始しました

  • http:// localhostを:8084 /
  • http:// localhostを:8087 /

セッション共有異なるサイト


関連読みます

おすすめ

転載: www.cnblogs.com/fishpro/p/spring-boot-study-sharedsession.html