springboot+redis+nginx+分布式session

第一步

启动一个redis

 我这里用的是windows版本的redis,进入磁盘后启动redis

启动命令:redis-server.exe redis.windows.conf

 

启动nginx

主要是配置一下

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    
    upstream tomcatserver {  
        server 127.0.0.1:8080; 
        server 127.0.0.1:8090;
    } 
    
    server {
        listen       80;
        server_name  localhost;

        location / {
            proxy_pass   http://tomcatserver;
            
            proxy_pass_header Server;
            proxy_set_header Host $http_host;
            proxy_set_header X_Real_IP $remote_addr;
            proxy_set_header X-Scheme $scheme;

        }
        
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    } 
}

然后开始写代码

使用springboot

在pom文件中加入依赖

 <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>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>

修改配置文件

spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=123456
@SpringBootApplication
@EnableRedisHttpSession
public class SpringbootApplication {


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

}
@RestController
public class Hello {


    @RequestMapping("/hello")
    public String Hellen(HttpServletRequest request) {
        HttpSession session = request.getSession();
        System.out.println(session.getId());
        System.out.println(System.currentTimeMillis());
        return session.getId() + "";
    }
}

在启动的时候指定端口号

 

可以看到已经是负载均很了,而且session共享了

注意一个坑

谷歌浏览器不要点刷新按钮,这个会全部请求在一个服务器上,不知道什么原因。

猜你喜欢

转载自www.cnblogs.com/songfahzun/p/10459478.html