Java秒杀系统方案优化【第三方登录】
一、qq登录
1.申请开发者账号
2.依赖
<dependency><groupId>org.apache.commons</groupId><artifactId>commons-io</artifactId><version>1.3.2</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId></dependency>
3.配置文件信息
constants.qqAppId=101513767
constants.qqAppSecret=b1d978cefcf405388893d8e686d307b0
constants.qqRedirectUrl=http://127.0.0.1:8080/QQLogin
4.读取配置文件QQ互联信息
package com.imooc.miaosha.entity;import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;/*** qq 登陆常量配置类*/
@Component
public class Constants {@Value("${constants.qqAppId}")private String qqAppId;@Value("${constants.qqAppSecret}")private String qqAppSecret;@Value("${constants.qqRedirectUrl}")private String qqRedirectUrl;@Value("${constants.weCatAppId}")private String weCatAppId;@Value("${constants.weCatAppSecret}")private String weCatAppSecret;@Value("${constants.weCatRedirectUrl}")private String weCatRedirectUrl;public String getQqAppId() {return qqAppId;}public void setQqAppId(String qqAppId) {this.qqAppId = qqAppId;}public String getQqAppSecret() {return qqAppSecret;}public void setQqAppSecret(String qqAppSecret) {this.qqAppSecret = qqAppSecret;}public String getQqRedirectUrl() {return qqRedirectUrl;}public void setQqRedirectUrl(String qqRedirectUrl) {this.qqRedirectUrl = qqRedirectUrl;}public String getWeCatAppId() {return weCatAppId;}public void setWeCatAppId(String weCatAppId) {this.weCatAppId = weCatAppId;}public String getWeCatAppSecret() {return weCatAppSecret;}public void setWeCatAppSecret(String weCatAppSecret) {this.weCatAppSecret = weCatAppSecret;}public String getWeCatRedirectUrl() {return weCatRedirectUrl;}public void setWeCatRedirectUrl(String weCatRedirectUrl) {this.weCatRedirectUrl = weCatRedirectUrl;}
}
5.数据接收的实体类
package com.imooc.miaosha.entity;/*** Created by Administrator on 2018/10/30/030.*/
public class QQUserInfo {private Integer ret;private String msg;private Integer is_lost;private String nickname;private String gender;private String province;private String city;private String year;private String constellation;private String figureurl;private String figureurl_1;private String figureurl_2;private String figureurl_qq;private String figureurl_qq_1;private String figureurl_qq_2;private String is_yellow_vip;private String vip;private String yellow_vip_level;private String level;private String is_yellow_year_vip;public String getFigureurl_qq() {return figureurl_qq;}public void setFigureurl_qq(String figureurl_qq) {this.figureurl_qq = figureurl_qq;}public Integer getRet() {return ret;}public void setRet(Integer ret) {this.ret = ret;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public Integer getIs_lost() {return is_lost;}public void setIs_lost(Integer is_lost) {this.is_lost = is_lost;}public String getNickname() {return nickname;}public void setNickname(String nickname) {this.nickname = nickname;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public String getProvince() {return province;}public void setProvince(String province) {this.province = province;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public String getYear() {return year;}public void setYear(String year) {this.year = year;}public String getConstellation() {return constellation;}public void setConstellation(String constellation) {this.constellation = constellation;}public String getFigureurl() {return figureurl;}public void setFigureurl(String figureurl) {this.figureurl = figureurl;}public String getFigureurl_1() {return figureurl_1;}public void setFigureurl_1(String figureurl_1) {this.figureurl_1 = figureurl_1;}public String getFigureurl_2() {return figureurl_2;}public void setFigureurl_2(String figureurl_2) {this.figureurl_2 = figureurl_2;}public String getFigureurl_qq_1() {return figureurl_qq_1;}public void setFigureurl_qq_1(String figureurl_qq_1) {this.figureurl_qq_1 = figureurl_qq_1;}public String getFigureurl_qq_2() {return figureurl_qq_2;}public void setFigureurl_qq_2(String figureurl_qq_2) {this.figureurl_qq_2 = figureurl_qq_2;}public String getIs_yellow_vip() {return is_yellow_vip;}public void setIs_yellow_vip(String is_yellow_vip) {this.is_yellow_vip = is_yellow_vip;}public String getVip() {return vip;}public void setVip(String vip) {this.vip = vip;}public String getYellow_vip_level() {return yellow_vip_level;}public void setYellow_vip_level(String yellow_vip_level) {this.yellow_vip_level = yellow_vip_level;}public String getLevel() {return level;}public void setLevel(String level) {this.level = level;}public String getIs_yellow_year_vip() {return is_yellow_year_vip;}public void setIs_yellow_year_vip(String is_yellow_year_vip) {this.is_yellow_year_vip = is_yellow_year_vip;}}
6.http工具类
package com.imooc.miaosha.util;import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;public class HttpClientUtils {public static final int connTimeout = 10000;public static final int readTimeout = 10000;public static final String charset = "UTF-8";private static HttpClient client = null;static {PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();cm.setMaxTotal(128);cm.setDefaultMaxPerRoute(128);client = HttpClients.custom().setConnectionManager(cm).build();}public static String postParameters(String url, String parameterStr)throws ConnectTimeoutException, SocketTimeoutException, Exception {return post(url, parameterStr, "application/x-www-form-urlencoded", charset, connTimeout, readTimeout);}public static String postParameters(String url, String parameterStr, String charset, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception {return post(url, parameterStr, "application/x-www-form-urlencoded", charset, connTimeout, readTimeout);}public static String postParameters(String url, Map<String, String> params)throws ConnectTimeoutException, SocketTimeoutException, Exception {return postForm(url, params, null, connTimeout, readTimeout);}public static String postParameters(String url, Map<String, String> params, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception {return postForm(url, params, null, connTimeout, readTimeout);}public static String get(String url) throws Exception {return get(url, charset, null, null);}public static String get(String url, String charset) throws Exception {return get(url, charset, connTimeout, readTimeout);}/*** 发送一个 Post 请求, 使用指定的字符集编码.** @param url* @param body RequestBody* @param mimeType 例如 application/xml "application/x-www-form-urlencoded"* a=1&b=2&c=3* @param charset 编码* @param connTimeout 建立链接超时时间,毫秒.* @param readTimeout 响应超时时间,毫秒.* @return ResponseBody, 使用指定的字符集编码.* @throws ConnectTimeoutException 建立链接超时异常* @throws SocketTimeoutException 响应超时* @throws Exception*/public static String post(String url, String body, String mimeType, String charset, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception {HttpClient client = null;HttpPost post = new HttpPost(url);String result = "";try {if (StringUtils.isNotBlank(body)) {HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset));post.setEntity(entity);}// 设置参数Builder customReqConf = RequestConfig.custom();if (connTimeout != null) {customReqConf.setConnectTimeout(connTimeout);}if (readTimeout != null) {customReqConf.setSocketTimeout(readTimeout);}post.setConfig(customReqConf.build());HttpResponse res;if (url.startsWith("https")) {// 执行 Https 请求.client = createSSLInsecureClient();res = client.execute(post);} else {// 执行 Http 请求.client = HttpClientUtils.client;res = client.execute(post);}result = IOUtils.toString(res.getEntity().getContent(), charset);} finally {post.releaseConnection();if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {((CloseableHttpClient) client).close();}}return result;}/*** 提交form表单** @param url* @param params* @param connTimeout* @param readTimeout* @return* @throws ConnectTimeoutException* @throws SocketTimeoutException* @throws Exception*/public static String postForm(String url, Map<String, String> params, Map<String, String> headers,Integer connTimeout, Integer readTimeout)throws ConnectTimeoutException, SocketTimeoutException, Exception {HttpClient client = null;HttpPost post = new HttpPost(url);try {if (params != null && !params.isEmpty()) {List<NameValuePair> formParams = new ArrayList<org.apache.http.NameValuePair>();Set<Map.Entry<String, String>> entrySet = params.entrySet();for (Map.Entry<String, String> entry : entrySet) {formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));}UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);post.setEntity(entity);}if (headers != null && !headers.isEmpty()) {for (Map.Entry<String, String> entry : headers.entrySet()) {post.addHeader(entry.getKey(), entry.getValue());}}// 设置参数Builder customReqConf = RequestConfig.custom();if (connTimeout != null) {customReqConf.setConnectTimeout(connTimeout);}if (readTimeout != null) {customReqConf.setSocketTimeout(readTimeout);}post.setConfig(customReqConf.build());HttpResponse res = null;if (url.startsWith("https")) {// 执行 Https 请求.client = createSSLInsecureClient();res = client.execute(post);} else {// 执行 Http 请求.client = HttpClientUtils.client;res = client.execute(post);}return IOUtils.toString(res.getEntity().getContent(), "UTF-8");} finally {post.releaseConnection();if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {((CloseableHttpClient) client).close();}}}/*** 发送一个 GET 请求** @param url* @param charset* @param connTimeout 建立链接超时时间,毫秒.* @param readTimeout 响应超时时间,毫秒.* @return* @throws ConnectTimeoutException 建立链接超时* @throws SocketTimeoutException 响应超时* @throws Exception*/public static String get(String url, String charset, Integer connTimeout, Integer readTimeout)throws ConnectTimeoutException, SocketTimeoutException, Exception {HttpClient client = null;HttpGet get = new HttpGet(url);String result = "";try {// 设置参数Builder customReqConf = RequestConfig.custom();if (connTimeout != null) {customReqConf.setConnectTimeout(connTimeout);}if (readTimeout != null) {customReqConf.setSocketTimeout(readTimeout);}get.setConfig(customReqConf.build());HttpResponse res = null;if (url.startsWith("https")) {// 执行 Https 请求.client = createSSLInsecureClient();res = client.execute(get);} else {// 执行 Http 请求.client = HttpClientUtils.client;res = client.execute(get);}result = IOUtils.toString(res.getEntity().getContent(), charset);} finally {get.releaseConnection();if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {((CloseableHttpClient) client).close();}}return result;}/*** 从 response 里获取 charset** @param ressponse* @return*/@SuppressWarnings("unused")private static String getCharsetFromResponse(HttpResponse ressponse) {// Content-Type:text/html; charset=GBKif (ressponse.getEntity() != null && ressponse.getEntity().getContentType() != null&& ressponse.getEntity().getContentType().getValue() != null) {String contentType = ressponse.getEntity().getContentType().getValue();if (contentType.contains("charset=")) {return contentType.substring(contentType.indexOf("charset=") + 8);}}return null;}/*** 创建 SSL连接** @return* @throws GeneralSecurityException*/private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {try {SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {return true;}}).build();SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {@Overridepublic boolean verify(String arg0, SSLSession arg1) {return true;}@Overridepublic void verify(String host, SSLSocket ssl) throws IOException {}@Overridepublic void verify(String host, X509Certificate cert) throws SSLException {}@Overridepublic void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {}});return HttpClients.custom().setSSLSocketFactory(sslsf).build();} catch (GeneralSecurityException e) {throw e;}}public static void main(String[] args) {try {String str = post("https://localhost:443/ssl/test.shtml", "name=12&page=34","application/x-www-form-urlencoded", "UTF-8", 10000, 10000);// String str=// get("https://localhost:443/ssl/test.shtml?name=12&page=34","GBK");/** Map<String,String> map = new HashMap<String,String>(); map.put("name",* "111"); map.put("page", "222"); String str=* postForm("https://localhost:443/ssl/test.shtml",map,null, 10000, 10000);*/System.out.println(str);} catch (ConnectTimeoutException e) {e.printStackTrace();} catch (SocketTimeoutException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}
}
7.url转码工具类
package com.imooc.miaosha.util;import java.io.UnsupportedEncodingException;public class URLEncodeUtil {private final static String ENCODE = "UTF-8";/*** URL 解码*/public static String getURLDecoderString(String str) {String result = "";if (null == str) {return "";}try {result = java.net.URLDecoder.decode(str, ENCODE);} catch (UnsupportedEncodingException e) {e.printStackTrace();}return result;}/*** URL 转码*/public static String getURLEncoderString(String str) {String result = "";if (null == str) {return "";}try {result = java.net.URLEncoder.encode(str, ENCODE);} catch (UnsupportedEncodingException e) {e.printStackTrace();}return result;}
}
8.登陆实现层
package com.imooc.miaosha.controller;import com.alibaba.fastjson.JSON;
import com.imooc.miaosha.entity.Constants;
import com.imooc.miaosha.entity.QQUserInfo;
import com.imooc.miaosha.service.MiaoshaUserService;
import com.imooc.miaosha.util.HttpClientUtils;
import com.imooc.miaosha.util.URLEncodeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;@Controller
public class QQController {/*** QQ :读取Appid相关配置信息静态类*/@Autowiredprivate Constants constants;@Autowiredprivate MiaoshaUserService userService;@Autowiredprivate LoginController loginController;/*** 获得跳转到qq登录页的url,前台直接a连接访问* @author wangsong* @date 2019年6月18日 下午8:29:20* @param session* @return* @throws Exception*/@GetMapping("/getQQCode")public String getCode(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model) throws Exception {// 拼接urlStringBuilder url = new StringBuilder();url.append("https://graph.qq.com/oauth2.0/authorize?");url.append("response_type=code");url.append("&client_id=" + constants.getQqAppId());// 回调地址 ,回调地址要进行Encode转码String redirect_uri = constants.getQqRedirectUrl();// 转码url.append("&redirect_uri=" + URLEncodeUtil.getURLEncoderString(redirect_uri));url.append("&state=ok");// HttpClientUtils.get(url.toString(), "UTF-8");//System.out.println(url.toString());model.addAttribute("url", url);return "redirect:"+url;}/*** 开始登录** @param code* @param* @param 实际业务:token过期调用刷新 token重新获取token信息* @param 数据库字段: accessToken,expiresIn,refreshToken,openId* @return* @throws Exception*/@GetMapping("/QQLogin")public String QQLogin(String code, Model model) throws Exception {// if (code != null) {// System.out.println(code);
// }//获取tocketMap<String, Object> qqProperties = getToken(code);//获取openId(每个用户的openId都是唯一不变的)String openId = getOpenId(qqProperties);//System.out.println(openId);qqProperties.put("openId",openId);//tocket过期刷新token//Map<String, Object> refreshToken = refreshToken(qqProperties);//获取数据QQUserInfo userInfo = getUserInfo(qqProperties);Long a=userService.ontSelectOfinsert(openId);return "redirect:"+"http://localhost:8080/login/do_login?mobile="+a+"&password=d3b1294a61a07da9b49b6e22b2cbd7f9&ifyzm=1";}/*** 获得token信息(授权,每个用户的都不一致) --> 获得token信息该步骤返回的token期限为一个月** @param (保存到Map<String,String> qqProperties)* @author wangsong* @return* @throws Exception* @date 2019年6月18日 下午8:56:45*/public Map<String, Object> getToken(String code) throws Exception {StringBuilder url = new StringBuilder();url.append("https://graph.qq.com/oauth2.0/token?");url.append("grant_type=authorization_code");url.append("&client_id=" + constants.getQqAppId());url.append("&client_secret=" + constants.getQqAppSecret());url.append("&code=" + code);// 回调地址String redirect_uri = constants.getQqRedirectUrl();// 转码url.append("&redirect_uri=" + URLEncodeUtil.getURLEncoderString(redirect_uri));// 获得tokenString result = HttpClientUtils.get(url.toString(), "UTF-8");//System.out.println("url:" + url.toString());// 把token保存String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(result, "&");String accessToken = StringUtils.substringAfterLast(items[0], "=");Long expiresIn = new Long(StringUtils.substringAfterLast(items[1], "="));String refreshToken = StringUtils.substringAfterLast(items[2], "=");//token信息Map<String,Object > qqProperties = new HashMap<String,Object >();qqProperties.put("accessToken", accessToken);qqProperties.put("expiresIn", String.valueOf(expiresIn));qqProperties.put("refreshToken", refreshToken);return qqProperties;}/*** 刷新token 信息(token过期,重新授权)** @return* @throws Exception*/@GetMapping("/refreshToken")public Map<String,Object> refreshToken(Map<String,Object> qqProperties) throws Exception {// 获取refreshTokenString refreshToken = (String) qqProperties.get("refreshToken");StringBuilder url = new StringBuilder("https://graph.qq.com/oauth2.0/token?");url.append("grant_type=refresh_token");url.append("&client_id=" + constants.getQqAppId());url.append("&client_secret=" + constants.getQqAppSecret());url.append("&refresh_token=" + refreshToken);System.out.println("url:" + url.toString());String result = HttpClientUtils.get(url.toString(), "UTF-8");// 把新获取的token存到map中String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(result, "&");String accessToken = StringUtils.substringAfterLast(items[0], "=");Long expiresIn = new Long(StringUtils.substringAfterLast(items[1], "="));String newRefreshToken = StringUtils.substringAfterLast(items[2], "=");//重置信息qqProperties.put("accessToken", accessToken);qqProperties.put("expiresIn", String.valueOf(expiresIn));qqProperties.put("refreshToken", newRefreshToken);return qqProperties;}/*** 获取用户openId(根据token)** @param 把openId存到map中* @return* @throws Exception*/public String getOpenId(Map<String,Object> qqProperties) throws Exception {// 获取保存的用户的tokenString accessToken = (String) qqProperties.get("accessToken");if (!StringUtils.isNotEmpty(accessToken)) {// return "未授权";}StringBuilder url = new StringBuilder("https://graph.qq.com/oauth2.0/me?");url.append("access_token=" + accessToken);String result = HttpClientUtils.get(url.toString(), "UTF-8");String openId = StringUtils.substringBetween(result, "\"openid\":\"", "\"}");return openId;}/*** 根据token,openId获取用户信息*/public QQUserInfo getUserInfo(Map<String,Object> qqProperties) throws Exception {// 取tokenString accessToken = (String) qqProperties.get("accessToken");String openId = (String) qqProperties.get("openId");if (!StringUtils.isNotEmpty(accessToken) || !StringUtils.isNotEmpty(openId)) {return null;}//拼接urlStringBuilder url = new StringBuilder("https://graph.qq.com/user/get_user_info?");url.append("access_token=" + accessToken);url.append("&oauth_consumer_key=" + constants.getQqAppId());url.append("&openid=" + openId);// 获取qq相关数据String result = HttpClientUtils.get(url.toString(), "UTF-8");Object json = JSON.parseObject(result, QQUserInfo.class);QQUserInfo userInfo = (QQUserInfo) json;return userInfo;}
}
9.前端
<a href="/getQQCode">获取qq登录连接</a>
10.效果图
二、手机验证码登录
1.申请签名模板(华为云)
2.依赖
<dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-core</artifactId><version>4.4.0</version></dependency><dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-dysmsapi</artifactId><version>1.0.0</version></dependency>
3.配置信息
send.mobile.regionId=cn-hangzhou
send.mobile.ignName=秒杀手机验证码登录
send.mobile.templateCode=SMS_191815051
send.mobile.accessKeyId=LTAI4GG5xDD3QdubcaSzDeqs
send.mobile.accessSecret=QZFPzdjaANPRbcXiVYFPsFQMGgaaED
4.工具类
package com.imooc.miaosha.config;import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.beans.factory.annotation.Value;public class SmsUtils {@Value("cn-hangzhou")private String regionId;@Value("秒杀手机验证码登录")private String SignName;@Value("SMS_191815051")private String TemplateCode;@Value("LTAI4GG5xDD3QdubcaSzDeqs")private String accessKeyId;@Value("QZFPzdjaANPRbcXiVYFPsFQMGgaaED")private String accessSecret;public String getAccessKeyId() {return accessKeyId;}public void setAccessKeyId(String accessKeyId) {this.accessKeyId = accessKeyId;}public String getAccessSecret() {return accessSecret;}public void setAccessSecret(String accessSecret) {this.accessSecret = accessSecret;}public String getRegionId() {return regionId;}public void setRegionId(String regionId) {this.regionId = regionId;}public String getSignName() {return SignName;}public void setSignName(String signName) {SignName = signName;}public String getTemplateCode() {return TemplateCode;}public void setTemplateCode(String templateCode) {TemplateCode = templateCode;}public void SendSms(String u_phone, String message){DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou",getAccessKeyId(), getAccessSecret());IAcsClient client = new DefaultAcsClient(profile);CommonRequest request = new CommonRequest();request.setSysMethod(MethodType.POST);request.setSysDomain("dysmsapi.aliyuncs.com");request.setSysVersion("2017-05-25");request.setSysAction("SendSms");request.putQueryParameter("RegionId", getRegionId());request.putQueryParameter("PhoneNumbers", u_phone);request.putQueryParameter("SignName", "秒杀手机验证码登录");request.putQueryParameter("TemplateCode", getTemplateCode());request.putQueryParameter("TemplateParam", "{\"code\":"+message+"}");System.out.println(getSignName());try {CommonResponse response = client.getCommonResponse(request);System.out.println(response.getData());} catch (ServerException e) {e.printStackTrace();} catch (ClientException e) {e.printStackTrace();}}
}
5.获取验证码
public String authcode_get(String u_phone) {String authcode = "1"+ RandomStringUtils.randomNumeric(5);//生成随机数,我发现生成5位随机数时,如果开头为0,发送的短信只有4位,这里开头加个1,保证短信的正确性redisService.set(MiaoshaUserKey.mobile,u_phone,authcode);//将验证码存入缓存smsUtils.SendSms(u_phone,authcode);//发送短息return authcode;}
6.验证码登录
public String authcode_select(String u_phone,String u_phone1) {String s = redisService.get(MiaoshaUserKey.mobile, u_phone, String.class);if(!s.equals(u_phone1)) {return "验证码错误";}return "登录成功";////成功后注册+登录+跳转到商品页面////}
7.登陆实现层
package com.imooc.miaosha.controller;import com.imooc.miaosha.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;@Controller
@RequestMapping("/login")
public class SmsController {@AutowiredSmsService smsService;@RequestMapping("/SendSms")@ResponseBodypublic String SendSms_login(String u_phone) {return "发送成功"+smsService.authcode_get(u_phone);}@RequestMapping("/yzmSms")@ResponseBodypublic String yzmSms_login(String u_phone, String code) {return smsService.authcode_select(u_phone,code);}
}
8.前端
<div class="col-md-5"><button class="btn btn-primary btn-block" type="submit" onclick="Alogin()">手机验证码登录</button></div>
9.效果图
Java秒杀系统方案优化【第三方登录】相关推荐
- Java秒杀系统方案优化 高性能高并发实战 学习笔记
秒杀系统 (一)搭建环境 自定义封装Result类 自定义封装CodeMsg类 集成redis和rabbit 封装RedisService类 断言和日志测试 (二)实现用户登录和分布式Session ...
- Java秒杀系统方案优化 高性能高并发实战视频
链接: https://pan.baidu.com/s/1VrtGT_04EUxlm_zcvnESVw 提取码: wjse 需要其他学习资料或者探讨Java相关开发技术可以关注"冰点IT&q ...
- 【在线网课】Java高性能高并发秒杀系统方案优化实战
java教程视频讲座简介: Java高性能高并发秒杀系统方案优化实战 Java秒杀系统方案优化 高性能高并发实战 以"秒杀"这一Java高性能高并发的试金石场景为例,带你通过一系列 ...
- java系统优化方案_Java秒杀系统方案优化 高性能高并发实战-一号门
类别: 视频 语言: Java 发布日期: 2019-03-02 介绍:以"秒杀"这一Java高性能高并发的试金石场景为例,带你通过一系列系统级优化,学会应对高并发. 第1章 课程 ...
- Java秒杀系统实战系列~数据库级别Sql的优化与代码的调整
摘要: 本篇博文是"Java秒杀系统实战系列文章"的第十三篇,从本篇文章开始我们将进入"秒杀代码优化"环节,本文将首先从数据库级别Sql的优化入手,结合调整秒杀 ...
- Java秒杀系统实战系列~基于Redisson的分布式锁优化秒杀逻辑
摘要: 本篇博文是"Java秒杀系统实战系列文章"的第十五篇,本文我们将借助综合中间件Redisson优化"秒杀系统中秒杀的核心业务逻辑",解决Redis的原子 ...
- Java秒杀系统实战系列~构建SpringBoot多模块项目
摘要:本篇博文是"Java秒杀系统实战系列文章"的第二篇,主要分享介绍如何采用IDEA,基于SpringBoot+SpringMVC+Mybatis+分布式中间件构建一个多模块的项 ...
- Java秒杀系统实战系列~JMeter压力测试重现秒杀场景中超卖等问题
摘要: 本篇博文是"Java秒杀系统实战系列文章"的第十二篇,本篇博文我们将借助压力测试工具Jmeter重现秒杀场景(高并发场景)下出现的各种典型的问题,其中最为经典的当属&quo ...
- Java实现集成Google邮箱第三方登录
Java实现集成Google邮箱第三方登录 前言 一.注册开发者账号 1.登录Google服务开发者平台,注册账号 2.创建OAuth 2.0客户端ID 二.代码实例 1.前端代码 a.加载客户端库 ...
最新文章
- js float 取精度
- 八皇后时间复杂度_LeetCode46:全排列(八皇后)
- Error:Cannot build artifact ‘ssm:war exploded‘ because it is included into a circular dependency
- 【.Net基础02】XML序列化问题
- vijos1237-隐形的翅膀【离散化】
- YOLOv3改进方法增加特征尺度和训练层数
- TechED2010与我(一)—— 初来乍到
- 分享40佳非常有创意的社交网络图标集
- IO子系统的层次结构
- Hadoop核心架构(1)
- 【转载】法线贴图Nomal mapping 原理
- Android RxJava2 浅析
- 【c语言】背包问题的贪心法
- 用python查询生成国内法定节假日安排
- 洛谷1251 餐巾计划问题
- 再见,拼多多!再见,黄铮!
- android控件属性大全
- Google Chrome v90.0.4430.212 正式版下载
- python进程已结束 退出代码0_PyCharm:进程以退出代码0结束
- 微信公众号支付 使用基于thinkphp 使用微信官网的sdk
热门文章
- 通过UDP广播获取网络中所有设备ip地址
- 看看人家用三天写出来的完整项目,直接惊艳了面试官!
- 自己写得循环往复的方阵,晒晒
- html网页制作摘要,网页制作初步—html摘要.ppt
- 一些解决问题的心得体会
- 【项目实战课】基于Pytorch的Semantic_Human_Matting(人像软分割)实战
- matlab 仿真入门,MATLAB/simulink仿真入门(第一节)
- C/C++程序开发: cJSON的使用(创建与解析JSON数据)
- 小鹅通前端春招一面面经(2021.4.1)
- 搞不明白的PS调色技巧视频教程