一、手机发送验证码流程:
二、定义用户服务,完成短信发送:
2.1 zyg-user-service工程添加如下依赖:
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>com.zelin</groupId><artifactId>zyg-user-interface</artifactId><version>2.0</version></dependency><dependency><groupId>com.zelin</groupId><artifactId>zyg-dao</artifactId><version>2.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-activemq</artifactId></dependency></dependencies>
2.2 zyg-user-service工程application.yml文件:
server:port: 7005spring:dubbo:protocol:name: dubboport: 20885registry:address: zookeeper://192.168.56.10:2181base-package: com.zelin.user.service.implapplication:name: zyg-user-serviceredis:host: 192.168.56.10activemq:broker-url: tcp://192.168.56.10:61616packages:trust-all: truelogging:level:com.zelin: debug
2.3 生成验证码并发送信息给activemq:
@Servicepublic class UserServiceImpl implements UserService {@Autowiredprivate StringRedisTemplate redisTemplate;@Autowiredprivate JmsMessagingTemplate jmsMessagingTemplate;//1. 生成验证码并发送消息@Overridepublic void getCode(String phone) {//1.1 生成六位数的验证码String code = (long) (Math.random()*1000000)+"";System.out.println("验证码:"+code);//1.2 将验证码存放到redis中redisTemplate.opsForValue().set(phone,code,200, TimeUnit.MINUTES);//1.3 将验证码信息发送给springboot-sms-service这个工程(它将监听我们发的信息)//1.3.1 重新组织数据(阿里云后台需要两个参数:手机号,验证号)Map<String,String> params = new HashMap<>();params.put("phone",phone);params.put("code",code);//1.3.2 将手机号及验证码发送出去jmsMessagingTemplate.convertAndSend("sms", params);}}
三、定义短信服务的监听方springboot-sms-service
3.1 添加依赖:
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.15</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.2.1</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.2.1</version></dependency><dependency><groupId>commons-lang</groupId><artifactId>commons-lang</artifactId><version>2.6</version></dependency><dependency><groupId>org.eclipse.jetty</groupId><artifactId>jetty-util</artifactId><version>9.3.7.v20160115</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.5</version><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-activemq</artifactId></dependency></dependencies></project>
3.2 引入工具类HttpUtils,用于发送http请求:
public class HttpUtils {/*** get** @param host* @param path* @param method* @param headers* @param querys* @return* @throws Exception*/public static HttpResponse doGet(String host, String path, String method,Map<String, String> headers,Map<String, String> querys)throws Exception {HttpClient httpClient = wrapClient(host);HttpGet request = new HttpGet(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}return httpClient.execute(request);}/*** post form** @param host* @param path* @param method* @param headers* @param querys* @param bodys* @return* @throws Exception*/public static HttpResponse doPost(String host, String path, String method,Map<String, String> headers,Map<String, String> querys,Map<String, String> bodys)throws Exception {HttpClient httpClient = wrapClient(host);HttpPost request = new HttpPost(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (bodys != null) {List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();for (String key : bodys.keySet()) {nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));}UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");request.setEntity(formEntity);}return httpClient.execute(request);}/*** Post String** @param host* @param path* @param method* @param headers* @param querys* @param body* @return* @throws Exception*/public static HttpResponse doPost(String host, String path, String method,Map<String, String> headers,Map<String, String> querys,String body)throws Exception {HttpClient httpClient = wrapClient(host);HttpPost request = new HttpPost(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (StringUtils.isNotBlank(body)) {request.setEntity(new StringEntity(body, "utf-8"));}return httpClient.execute(request);}/*** Post stream** @param host* @param path* @param method* @param headers* @param querys* @param body* @return* @throws Exception*/public static HttpResponse doPost(String host, String path, String method,Map<String, String> headers,Map<String, String> querys,byte[] body)throws Exception {HttpClient httpClient = wrapClient(host);HttpPost request = new HttpPost(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (body != null) {request.setEntity(new ByteArrayEntity(body));}return httpClient.execute(request);}/*** Put String* @param host* @param path* @param method* @param headers* @param querys* @param body* @return* @throws Exception*/public static HttpResponse doPut(String host, String path, String method,Map<String, String> headers,Map<String, String> querys,String body)throws Exception {HttpClient httpClient = wrapClient(host);HttpPut request = new HttpPut(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (StringUtils.isNotBlank(body)) {request.setEntity(new StringEntity(body, "utf-8"));}return httpClient.execute(request);}/*** Put stream* @param host* @param path* @param method* @param headers* @param querys* @param body* @return* @throws Exception*/public static HttpResponse doPut(String host, String path, String method,Map<String, String> headers,Map<String, String> querys,byte[] body)throws Exception {HttpClient httpClient = wrapClient(host);HttpPut request = new HttpPut(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}if (body != null) {request.setEntity(new ByteArrayEntity(body));}return httpClient.execute(request);}/*** Delete** @param host* @param path* @param method* @param headers* @param querys* @return* @throws Exception*/public static HttpResponse doDelete(String host, String path, String method,Map<String, String> headers,Map<String, String> querys)throws Exception {HttpClient httpClient = wrapClient(host);HttpDelete request = new HttpDelete(buildUrl(host, path, querys));for (Map.Entry<String, String> e : headers.entrySet()) {request.addHeader(e.getKey(), e.getValue());}return httpClient.execute(request);}private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {StringBuilder sbUrl = new StringBuilder();sbUrl.append(host);if (!StringUtils.isBlank(path)) {sbUrl.append(path);}if (null != querys) {StringBuilder sbQuery = new StringBuilder();for (Map.Entry<String, String> query : querys.entrySet()) {if (0 < sbQuery.length()) {sbQuery.append("&");}if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {sbQuery.append(query.getValue());}if (!StringUtils.isBlank(query.getKey())) {sbQuery.append(query.getKey());if (!StringUtils.isBlank(query.getValue())) {sbQuery.append("=");sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));}}}if (0 < sbQuery.length()) {sbUrl.append("?").append(sbQuery);}}return sbUrl.toString();}private static HttpClient wrapClient(String host) {HttpClient httpClient = new DefaultHttpClient();if (host.startsWith("https://")) {sslClient(httpClient);}return httpClient;}private static void sslClient(HttpClient httpClient) {try {SSLContext ctx = SSLContext.getInstance("TLS");X509TrustManager tm = new X509TrustManager() {public X509Certificate[] getAcceptedIssuers() {return null;}public void checkClientTrusted(X509Certificate[] xcs, String str) {}public void checkServerTrusted(X509Certificate[] xcs, String str) {}};ctx.init(null, new TrustManager[] { tm }, null);SSLSocketFactory ssf = new SSLSocketFactory(ctx);ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);ClientConnectionManager ccm = httpClient.getConnectionManager();SchemeRegistry registry = ccm.getSchemeRegistry();registry.register(new Scheme("https", 443, ssf));} catch (KeyManagementException ex) {throw new RuntimeException(ex);} catch (NoSuchAlgorithmException ex) {throw new RuntimeException(ex);}}}
3.3 监听我们发送的消息
/*** ------------------------------* 功能:* 作者:WF* 微信:hbxfwf13590332912* 创建时间:2021/8/10-16:37* ------------------------------*/@Componentpublic class MyMessageListener {@JmsListener(destination = "sms")public void getMessage(Map<String,String> params){//1. 获取手机号String phone = params.get("phone");//2. 获取验证码String code = params.get("code");System.out.println("code = " + code);//3. 使用工具类发送信息给阿里云sendMessage(phone,code);}private void sendMessage(String phone,String code){String host = "http://dingxin.market.alicloudapi.com";String path = "/dx/sendSms";String method = "POST";String appcode = "7ba36df9be9e4518bda04ba2702b8fb0";Map<String, String> headers = new HashMap<String, String>();//最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105headers.put("Authorization", "APPCODE " + appcode);Map<String, String> querys = new HashMap<String, String>();querys.put("mobile",phone);querys.put("param", "code:" + code);querys.put("tpl_id", "TP1711063");Map<String, String> bodys = new HashMap<String, String>();try {/*** 重要提示如下:* HttpUtils请从* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java* 下载** 相应的依赖请参照* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml*/HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);System.out.println(response.toString());//获取response的body//System.out.println(EntityUtils.toString(response.getEntity()));} catch (Exception e) {e.printStackTrace();}}}
3.4 前端页面编写:
3.4.1 在docker下nginx服务器中配置user静态资源:
3.4.2 配置nginx服务器:
第1步:在/mydata/nginx/conf/nginx.conf下添加上服务器:
upstream user{server 192.168.56.1:9005;}
第2步:在/mydata/nginx/conf/conf.d/zeyigou.conf配置自己的反向代理服务器
server {listen 80;server_name user.zeyigou.com;location / {proxy_pass http://user;proxy_set_header Host $host:$server_port;}include /etc/nginx/static.conf;}
第3步:重启nginx服务器:
docker restart nginx
第4步:修改zyg-user-web中的静态页面,将其中的静态路径前添加:/static/user/
第5步:在swithHost中配置域名服务器:
四、注册用户:
4.1 在前端register.html中提交表单 :
4.2 在zyg-user-web中添加注册方法:
//3. 添加用户@RequestMapping("user/add")public String add(UserEntity userEntity,String validCode){//3.1 比较用户输入的验证码与redis中的验证码是否一致boolean b = userService.purdgeCode(validCode,userEntity.getPhone());//3.2 如果比较相等,就添加用户if(b){userService.add(userEntity);}return "register";}
4.3 在zyg-user-service模块完成验证码比较及用户添加
/*** 功能: 比较验证码是否相等* 参数:* 返回值: boolean* 时间: 2021/8/11 14:32*/@Overridepublic boolean purdgeCode(String validCode, String phone) {//1. 根据手机号得到原来的验证码String code = redisTemplate.opsForValue().get(phone);//2. 判断是否存在if(StringUtils.isNotBlank(validCode) && StringUtils.isNotBlank(code) && validCode.equals(code)){return true;}return false;}/*** 功能: 注册新用户* 参数:* 返回值: void* 时间: 2021/8/11 14:33*/@Overridepublic void add(UserEntity userEntity) {userEntity.setCreated(new Date());userEntity.setStatus("y");//1. 将原来的密码进行加密BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();String pwd = encoder.encode(userEntity.getPassword());//2. 重新保存到数据库中userEntity.setPassword(pwd);this.save(userEntity);}
4.4 数据库中查看添加的用户结果 :

