springboot+redis單點登陸session共享

單點登陸(SSO)的定義是在多個應用系統中,用戶只須要登陸一次就能夠訪問全部相互信任的應用系統。java

如今就是用springboot和redis來完成session共享。web

1.導入相關依賴。(web和redis相關)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.配置redisspring

@Configuration  
@EnableRedisHttpSession  
public class RedisSessionConfig {  
}

其中@EnableRedisHttpSession註解,開啓redis集中式session管理,把全部的session都存放到了redis中springboot

3.配置application.yml文件,端口的設置以及redis的鏈接地址和端口號配置session

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

爲了模擬共享,須要開啓另個服務,server端口號能夠設置8081,其餘保持不變app

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

4.控制層代碼 spring-boot

@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和server8081code

訪問http://localhost:8080/admin/setSessionId 設置sessionIdserver

查看redis,能夠看到redis中已經存在springsession相關數據,此時也能夠看到設置的sessionId

訪問另外一個服務http://localhost:8081/admin/getSessionId

不一樣服務sessionId共享成功。

以上就是session共享簡單的小例子。

相關文章
相關標籤/搜索