在微服務架構下,須要支持分佈式Session,分佈式Session能夠經過Redis來實現,也能夠經過數據庫來實現,本文介紹Redis實現。java
下載地址:https://github.com/MSOpenTech...
選擇對應的版本安裝。 git
進入安裝目錄啓動Redis。github
<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> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency>
yml配置以下:web
# Redis服務器地址 spring.redis.host=localhost # Redis服務器鏈接端口 spring.redis.port=6379
config配置以下:redis
@Configuration @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400 * 30) public class SessionConfig { }
登錄成功後設置Session信息,代碼以下:spring
@Component @RestController public class LoginController { @RequestMapping("/login") public String login(@RequestBody String userId, HttpSession session) throws Exception { session.setAttribute(Constants.SESSION_USER_ID, userId); return "Login success."; } }
沒有成功登錄並設置Session,須要跳轉到錯誤頁面, 代碼實例以下:數據庫
@Configuration public class SessionFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (isNeedAuth(request)) { Object userIdObject = request.getSession().getAttribute(Constants.SESSION_USER_ID); if (null == userIdObject) { response.sendRedirect("/errorPage"); } } filterChain.doFilter(request, response); } }
以上爲實現Redis Session的全部步驟,完整實例代碼掃碼加入微信公衆號並回復:webfullstack,獲取倉庫地址。 apache
end.服務器
站點: http://javashizhan.com/微信
微信公衆號:
<font color="#F4B183">加入知識星球,參與討論,更多實戰代碼分享! </font>
https://t.zsxq.com/RNzfi2j