1. 程式人生 > >SpringBoot+Redis+Nginx實現負載均衡以及Session快取共享

SpringBoot+Redis+Nginx實現負載均衡以及Session快取共享

1.環境資訊
nginx-1.11.10
redis-latest包(redis windows版本)
springboot1.5.1.RELEASE

3.nginx和redis解壓縮即可,並正常啟動


4.springboot整合Redis以及springboot,需要在POM檔案中增加依賴

    <?xml version="1.0" encoding="UTF-8"?>
    <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.example</groupId> <artifactId>demo3</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging>
<name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.1.RELEASE</version
>
<relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.3.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <version>1.3.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

5.新建Controller類DemoController.java

@Controller
public class DemoController {
    @Autowired  
    DemoService demoService;  
     
    @RequestMapping("testcache")
    @ResponseBody
    public String testCache(@RequestParam String key){
        String s = demoService.testCache(key);
        return s;
    }
    
    @RequestMapping("/getseansession")
    @ResponseBody
    public Map<String,String> getSession(HttpServletRequest request){
        Map<String,String> attributeMap = new HashMap<String, String>();
        request.getSession().setAttribute("message", request.getRequestURI());
        attributeMap.put("message", request.getRequestURI());
        System.out.println("sessionID:" + request.getSession().getId());
        return attributeMap;
    }
}

6.新建Service類DemoService.java

@Service
public class DemoService {
    @Cacheable(value = "keycache")
    public String testCache(String key){
        System.out.println("testCache:" + key);
        return key;
    }
}

7.新建RedisConfig類增加@EnableRedisHttpSession註解

@Configuration  
@EnableCaching
@EnableRedisHttpSession
public class RedisConfig{
}

8.application.properties檔案配置,其中為了測試ngnix負載均衡功能,本工程配置為8080埠,另一個springboot工程可以配置為別的埠,比如8088,以便啟動兩個Server

#redis spring.redis.password=xxx
#spring.redis.database= # database name  
spring.redis.hostname=127.0.0.1 # server host
spring.redis.port=6379  
spring.redis.pool.maxActive=8  
spring.redis.pool.maxWait=-1  
spring.redis.pool.maxIdle=8  
spring.redis.pool.minIdle=0  
spring.redis.timeout=0

#tomcat port configuration
server.port=8080

可以看到啟動了兩個Server,DemoApplication和DemoApplication(1)


9.ngnix.conf配置檔案中配置負載均衡策略

upstream test {
        server localhost:8080;
        server localhost:8088;
    }
    
    server {
        listen       80;
        server_name  localhost;
        client_max_body_size 1024M;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        #location / {
        #    root   html;
        #    index  index.html index.htm;
        #}

        location / {
            proxy_pass http://test/getseansession;
            proxy_set_header Host $host:$server_port;
        }

10.訪問http://localhost,會發現http請求交替訪問後端兩個server。且sessionID是一樣的“sessionID:ad0cbb3b-d24d-4d61-87ac-b9ddcfeccaa4”。並沒有因為server不一致而sessionID不同


使用RedisClient連線Redis Server,確實儲存了一個sessionID,如下:

11.maven工程目錄

12.實際操縱過程中遇到一個問題:啟動springboot工程的時候報錯“java.lang.IllegalStateException: Cannot load configuration class: org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration”


解決方法:對於spring-context-support依賴,增加了一個version,且版本為4.3.5.RELEASE。啟動,未報錯,問題解決。沒配version的時候,預設是4.3.6.RELEASE,奇怪。後續有時間再研究。

        <dependency>
             <groupId>org.springframework</groupId>
             <artifactId>spring-context-support</artifactId>
             <version>4.3.5.RELEASE</version>
        </dependency>