首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

SpringBoot 实现Session共享实战

HttpSession,是通过Servlet容器创建并进行管理的,创建成功以后将会保存在内存中,这里将会使用Redis解决session共享的问题。

创建项目

添加pom

添加相关的maven

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

org.springframework.boot

spring-boot-starter-parent

2.3.1.RELEASE

com.example

demo

0.0.1-SNAPSHOT

demo

Demo project for Spring Boot

1.8

org.springframework.boot

spring-boot-starter-data-redis

2.3.1.RELEASE

io.lettuce

lettuce-core

6.0.0.M1

redis.clients

jedis

3.3.0

org.springframework.session

spring-session-data-redis

2.3.0.RELEASE

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-test

test

org.junit.vintage

junit-vintage-engine

org.springframework.boot

spring-boot-maven-plugin

配置redis连接

配置redis连接

spring:

redis:

database: 0

host: 106.53.115.12

port: 6379

password: 12345678

jedis:

pool:

max-active: 8

max-idle: 8

max-wait: -1ms

min-idle: 0

创建Controller用来执行测试操作

package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController

public class HelloController {

@PostMapping("/save")

public String saveName(String name, HttpSession session){

session.setAttribute("name", name);

return "8080";

}

@GetMapping("/get")

public String getName(HttpSession httpSession){

return httpSession.getAttribute("name").toString();

}

}

Nginx 负载均衡

mingming@xiaoming-pc:~$ sudo apt-get install nginx

修改配置文件

upstream sang.com {

server 192.168.0.1:8080 weight = 1;

server 192.168.0.2:8080 weight = 1;

}

server {

listen 80;

server_name localhost;

location / {

proxy_pass http://sang.com;

proxy_redirect default;

}

}

请求分发

保存数据

获取数据

小明菜市场

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20200623A0TY3Q00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券