springboot+redis单点登录session共享

单点登录(SSO)的定义是在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统。

现在就是用springboot和redis来完成session共享。

1.导入相关依赖。(web和redis相关)

<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.1.RELEASE</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<!-- redis -->
		<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>

	</dependencies>

2.配置redis

@Configuration  
@EnableRedisHttpSession  
public class RedisSessionConfig {  
}  

其中@EnableRedisHttpSession注解,开启redis集中式session管理,把所有的session都存放到了redis中

3.配置application.yml文件,端口的设置以及redis的连接地址和端口号配置

server:
  port: 8080
spring:
  redis:
    host: 192.168.56.150
    port: 6379

为了模拟共享,需要开启另个服务,server端口号可以设置8081,其他保持不变

server:
  port: 8081
spring:
  redis:
    host: 192.168.56.150
    port: 6379

4.控制层代码 

@RestController  
@RequestMapping("/admin")
public class RedisController {  
	
    @GetMapping("/setSessionId")  
    public String setredisResult(HttpServletRequest request){
    	HttpSession session = request.getSession();
    	session.setAttribute("sessionId","100");
    	return "设置ok...";
    }
    @GetMapping("/getSessionId")
	public String redisResult(HttpServletRequest request) {
		HttpSession session = request.getSession();
		String sessid = (String) session.getAttribute("sessionId");
		return "sessionId:"+sessid;
	}
} 

5.运行server8080和server8081

访问http://localhost:8080/admin/setSessionId 设置sessionId

查看redis,可以看到redis中已经存在springsession相关数据,此时也可以看到设置的sessionId

125355_zcJX_3805335.png

访问另一个服务http://localhost:8081/admin/getSessionId

125630_wiue_3805335.png

不同服务sessionId共享成功。

以上就是session共享简单的小例子。

 

 

转载于:https://my.oschina.net/u/3805335/blog/1807739

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值