玩轉spring boot——負載均衡與session共享

 前言javascript


 

當項目上線後,若是要修復bug或擴充功能,都須要重啓tomcat服務。此時,正在使用應用的用戶們就須要等待服務器的重啓,而這就會形成很差的用戶體驗。還有,當僅僅只有一臺tomcat服務時,若是CPU或內存達到極限,就會很難頂住壓力。而負載均衡就是解決這些問題的方案。css

 項目的演化以下:html

 

由一臺單tomcat服務器淨化到多臺服務器組成的集羣。java

圖中的nginx做爲反向代理的負載均衡服務器,nginx把請求轉發到局域網內的tomcat服務器上。nginx

 中間的session共享,須要使用redis來實現。git

準備工做github

pom.xml:web

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.github.carter659</groupId>
    <artifactId>spring11</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
    </parent>

    <name>spring11</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
pom.xml

 

MainController.java:redis

package com.github.carter659.spring11;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 博客出處:http://www.cnblogs.com/GoodHelper/
 * 
 * @author 劉冬
 *
 */
@Controller
public class MainController {

    private static final String STR_SESSION_KEY = "name";

    @GetMapping("/")
    public String index() {
        return "index";
    }

    @PostMapping("/setSession")
    public @ResponseBody Map<String, Object> setSession(String value, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        request.getSession().setAttribute(STR_SESSION_KEY, value);
        map.put("msg", "ok");
        return map;
    }

    @PostMapping("/getSession")
    public @ResponseBody Map<String, Object> getSession(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        HttpSession session = request.getSession();
        Object value = session.getAttribute(STR_SESSION_KEY);
        map.put("value", value);
        map.put("id", session.getId());
        map.put("port", request.getLocalPort());
        map.put("msg", "ok");
        return map;
    }

}
MainController.java

 

App.java:spring

package com.github.carter659.spring11;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * 博客出處:http://www.cnblogs.com/GoodHelper/
 *
 */
@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

}
App.java

 

index.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>玩轉spring boot——負載均衡與session同步</title>
<style type="text/css">
/*<![CDATA[*/
tr {
    text-align: center;
    COLOR: #0076C8;
    BACKGROUND-COLOR: #F4FAFF;
}
/*]]>*/
</style>
<script src="//cdn.bootcss.com/angular.js/1.5.6/angular.min.js"></script>
<script type="text/javascript">
    /*<![CDATA[*/
    var app = angular.module('app', []);
    app.controller('MainController', function($rootScope, $scope, $http) {

        $scope.value = '劉冬';

        $scope.setSession = function() {
            $http({
                url : '/setSession?value=' + $scope.value,
                method : 'POST'
            });
        }

        $scope.getSession = function() {
            $http({
                url : '/getSession',
                method : 'POST'
            }).success(function(r) {
                $scope.sesssionId = r.id
                $scope.sesssion = r.value
                $scope.port = r.port
            });
        }
    });

    /*]]>*/
</script>
</head>
<body ng-app="app" ng-controller="MainController">
    <h1>玩轉spring boot——負載均衡與session同步</h1>
    <h4>
        <a href="http://www.cnblogs.com/GoodHelper/">from 劉冬的博客</a>
    </h4>
    <input type="text" ng-model="value" />
    <input type="button" value="設置" ng-click="setSession()" />
    <br />
    <input type="button" value="獲取" ng-click="getSession()" />
    <br />
    <h3>結果:</h3>
    <table cellspacing="1" style="background-color: #a0c6e5">
        <thead>
            <tr>
                <td>屬性</td>
                <td></td>
            </tr>
        </thead>
        <tr>
            <td>session id</td>
            <td>{{sesssionId}}</td>
        </tr>
        <tr>
            <td>session值</td>
            <td>{{sesssion}}</td>
        </tr>
        <tr>
            <td>本地端口</td>
            <td>{{port}}</td>
        </tr>
    </table>


    <br />
    <a href="http://www.cnblogs.com/GoodHelper/">點擊訪問原版博客</a>
</body>
</html>
index.html

 

 

1、負載均衡


 

首先,進去src目錄後,maven打包:mvn package

啓動兩個spring boot mvc應用實例,分別配置8080和8081端口:

java -jar -Dserver.port=8080 target/spring11-0.0.1-SNAPSHOT.jar
java -jar -Dserver.port=8081 target/spring11-0.0.1-SNAPSHOT.jar

 

接着,下載nginx

修改nginx的配置文件「conf/nginx.conf」

加入以下代碼:

upstream tomcat {
		server localhost:8080;
		server localhost:8081;
	}

    server {
        listen       80;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm;
		proxy_redirect off;
		proxy_pass http://tomcat;
        }
}

upstream節點爲負載均衡配置
下面指定了兩個server實例,對於localhost的8080和8081端口
server節點監聽80端口,會跳轉到反向代理的名稱爲協議「http://tomcat」的upstream上
這裏的「http://tomcat」,要與upstream設置的名稱相同


運行nginx.exe:


輸入http://localhost網址

 

發現,在訪問80端口的網站時,會顯示8080和8081的本地端口。這樣,負載均衡就輕鬆實現了。不過此時,並未實現session共享

 

2、sesstion共享


 

 

spring boot的session共享至關簡單,只須要添加maven依賴便可,其餘地方不須要改動

        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>

 

接下來,啓動redis-server.exe:

 

 

再次刷新http://localhost網址測試:

 

此時,sessionId保存不變,也可以修改session的值了。

 

補充:因爲我測試環境是本身的電腦,若是部署到其餘環境,須要在「application.properties」中修改redis的host、端口和密碼。

 

總結


 

由此看出spring boot在管理session上很是方便。在平常運維中,只須要擴展mvc應用的實例即可以實現負載。一般在服務器中,會跑一個檢測cpu和內存的運維程序,當發現CPU或內存佔用率高的時候,自動調用雲服務商(如阿里雲)的sdk來建立若干個新的服務器;當cpu內存降下來後,再去把以前建立的服務器釋放掉,就能實現彈性計算。同理也能夠結合docker,這樣實現的會更完美些。

 

代碼:https://github.com/carter659/spring-boot-11.git

 

若是你以爲個人博客對你有幫助,能夠給我點兒打賞,左側微信,右側支付寶。

有可能就是你的一點打賞會讓個人博客寫的更好:)

 

返回玩轉spring boot系列目錄

相關文章
相關標籤/搜索