java版spring cloud分布式微服务(二)Session共享-b2b2c小程序电子商务

Dawn ·
更新时间:2024-09-20
· 719 次阅读

下面我们将在springcloud微服务项目中,使用redis实现简单高效的session共享。
了解springcloud架构可以加求求:三五三六二四七二五九
新建一个spring boot项目,命名springcloud-session-redis

POM依赖配置

4.0.0 com.carry springcloud-session-redis 0.0.1-SNAPSHOT jar springcloud-session-redis Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 2.0.4.RELEASE UTF-8 UTF-8 1.8 Finchley.SR1 org.springframework.boot spring-boot-starter-data-redis org.springframework.session spring-session-data-redis org.apache.commons commons-pool2 org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.boot spring-boot-starter-actuator org.springframework.cloud spring-cloud-dependencies ${spring-cloud.version} pom import org.springframework.boot spring-boot-maven-plugin

配置文件
在application.yml中加入redis、eureka、port等配置

server: port: 8090 spring: application: name: service-session-redis redis: host: 192.168.68.100 port: 6379 password: 123456 timeout: 6000ms lettuce: pool: max-active: 8 max-wait: -1ms max-idle: 8 min-idle: 0 database: 0 eureka: client: serviceUrl: defaultZone: http://admin:123456@localhost:8761/eureka/ management: endpoints: web: exposure: include: "*" cors: allowed-origins: "*" allowed-methods: "*"

Redis Session配置类

package com.carry.config; import org.springframework.context.annotation.Configuration; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; @Configuration @EnableRedisHttpSession public class RedisSessionConfig { }

控制层Controller中添加测试方法

package com.carry.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RefreshScope public class UserManagementController { /** * redis sesion共享 * * @param request * @return */ @GetMapping("/getUser") public String getUser(HttpServletRequest request) { HttpSession session = request.getSession(); String username = (String) session.getAttribute("username"); if (StringUtils.isEmpty(username)) { username = "testSessionRedis|" + System.currentTimeMillis(); session.setAttribute("username", username); } System.out.println("访问端口:" + request.getServerPort()); return username; } }
作者:m0_46413263



b2b 微服务 JAVA spring 程序 电子 电子商务 session

需要 登录 后方可回复, 如果你还没有账号请 注册新账号