1.准备工作
Nginx用来实现负载均衡Nginx下载点这里
Redis用来实现Session共享,选择3.x版本Redis下载点这里
2.Session共享
pom.xml加入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
application.properties加入redis配置
########################################################
### Redis+Session
########################################################
spring.redis.database=0
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.timeout=0
spring.session.store-type=redis
创建RedisConfig类
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
@Configuration
@EnableCaching
@EnableRedisHttpSession
public class RedisConfig{
}
启动没报错的话,redis实现session共享就完成了。
如果报错的话,可能是你redis服务器版本太低,所以建议下载3.x以上。
3.Nginx负载均衡
解压完打开conf文件夹,更改nginx.conf配置。注意upstream后的名称要和proxy_pass配置一样
upstream test {
server localhost:8080;
server localhost:8081;
}
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
#location / {
# root html;
# index index.html index.htm;
#}
location / {
proxy_pass http://test;
proxy_set_header Host $host:$server_port;
}
4. 运行
在8080端口运行项目,在8081端口运行项目
打开Nginx.exe
输入http://localhost,看两个项目的后台信息,可以发现项目被轮询访问。