创建工程,导入session,web,redis的依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</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-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
在application.properties中配置redis
spring.redis.host=192.168.65.128
spring.redis.port=6379
spring.redis.password=hx
spring.redis.database=0
创建HelloController类
package org.hx.springboot_redisnginx_demo35;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
@RestController
public class HelloController {
@Value("${server.port}")
Integer port;
@GetMapping("/set")
public String set(HttpSession session) {
session.setAttribute("user", "hx");
return String.valueOf(port);
}
@GetMapping("/get")
public String get(HttpSession session) {
return session.getAttribute("user") + ":" + port;
}
}
在CentOS中配置nginx.conf和default.conf文件
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
upstream hx.org{
server 192.168.xx.128:8080 weight=1;
server 192.168.xx.128:8081 weight=2;
}
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
"nginx.conf" 36L, 743C
upstream:表示配置上游服务器,里边配置的是一个个的单独服务
hx.org:表示服务器集群的名字
weight:表示服务的权重,意味者将有多少比例的请求从 Nginx 上转发到该服务上
server {
listen 80;
listen [::]:80;
server_name localhost;
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
location / {
proxy_pass http://hx.org;
proxy_redirect default;
root /usr/share/nginx/html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
"default.conf" 48L, 1167C
location中的 proxy_pass: 表示请求转发的地址,http://hx.org 表示拦截到所有的请求,转发转发到刚刚配置好的服务集群中
proxy_redirect 表示设置当发生重定向请求时,nginx 自动修正响应头数据(默认是 Tomcat 返回重定向,此时重定向的地址是 Tomcat 的地址,我们需要将之修改使之成为 Nginx 的地址)。
将项目打包拷贝到CentOS7.9中,启动redis和nginx,并启动项目
java -jar springboot_redisnginx_demo35-0.0.1-SNAPSHOT.jar --server.port=8080 &
java -jar springboot_redisnginx_demo35-0.0.1-SNAPSHOT.jar --server.port=8081 &