1.1 为什么要使用jwt+redis实现用户登录?
因为如今的互联网应用基本上都是分布式的,正因为分布式的原因所以我们的程序面临着session共享的问题,我们都知道session只能在目标服务器中才能够保存,在多节点的分布式应用中这样显然不是特别好,所以我们需要使用jwt+redis实现分布式共享session的一个操作。
2.1 能够使用nginx的iphash负载均衡策略就能实现session同步为什么还要使用redis保存session?
众所周知nginx是一个高性能的反向代理服务器,但是我们的后端应用服务器能够接受的请求量不是那么的多,如果我们的请求数达到了一定的峰值,占满了后端tomcat应用服务器的所有请求队列,那么这个时候就进入了一个阻塞状态,所以共享session是必然需要的。
3.1 如何使用JWT+Redis实现微信登录以及实现token共享
1. 在微信公众平台总添加我们项目的所属域名映射
需要注意的是回调域不需要加任何协议(http/https)也不需要加任何路径,单独只要域名就好
2. 导入相关maven依赖
<!--微信公众模块 sdk-->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-mp</artifactId>
<version>3.6.0</version>
</dependency>
<!--JWT所需依赖-->
<!-- https://mvnrepository.com/artifact/com.auth0/java-jwt -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>${jwt.version}</version>
</dependency>
<!--redis所需依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
3. 编写配置类 WechatAccountConfig
与WechatOpenConfig
package com.qingyun.wechat_ordersys.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* Created with IntelliJ IDEA.
* User: 李敷斌.
* Date: 2020-01-30
* Time: 11:51
* Explain: 微信公众模块账号相关配置类
*/
@Component
@Data
@ConfigurationProperties(prefix = "wechat")
public class WechatAccountConfig {
//开放平台 appid
private String openAppId;
//开放平台 app密钥
private String openAppSecret;
}
=================================================================
package com.qingyun.wechat_ordersys.config;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
/**
* Created with IntelliJ IDEA.
* User: 李敷斌.
* Date: 2020-02-04
* Time: 15:33
* Explain: 微信商户平台配置类
*/
@Component
public class WechatOpenConfig {
@Autowired
private WechatAccountConfig accountConfig;
@Bean
public WxMpService wxOpenService(){
WxMpService wxMpService=new WxMpServiceImpl();
wxMpService.setWxMpConfigStorage(this.wxOpenConfigStorage());
return wxMpService;
}
@Bean
public WxMpConfigStorage wxOpenConfigStorage(){
WxMpDefaultConfigImpl wxMpDefaultConfig=new WxMpDefaultConfigImpl();
wxMpDefaultConfig.setAppId(accountConfig.getOpenAppId());
wxMpDefaultConfig.setSecret(accountConfig.getOpenAppSecret</