一、手机发送验证码流程:

image.png

二、定义用户服务,完成短信发送:

2.1 zyg-user-service工程添加如下依赖:

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.zelin</groupId>
  8. <artifactId>zyg-user-interface</artifactId>
  9. <version>2.0</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>com.zelin</groupId>
  13. <artifactId>zyg-dao</artifactId>
  14. <version>2.0</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.springframework.boot</groupId>
  18. <artifactId>spring-boot-starter-data-redis</artifactId>
  19. </dependency>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-activemq</artifactId>
  23. </dependency>
  24. </dependencies>

2.2 zyg-user-service工程application.yml文件:

  1. server:
  2. port: 7005
  3. spring:
  4. dubbo:
  5. protocol:
  6. name: dubbo
  7. port: 20885
  8. registry:
  9. address: zookeeper://192.168.56.10:2181
  10. base-package: com.zelin.user.service.impl
  11. application:
  12. name: zyg-user-service
  13. redis:
  14. host: 192.168.56.10
  15. activemq:
  16. broker-url: tcp://192.168.56.10:61616
  17. packages:
  18. trust-all: true
  19. logging:
  20. level:
  21. com.zelin: debug

2.3 生成验证码并发送信息给activemq:

  1. @Service
  2. public class UserServiceImpl implements UserService {
  3. @Autowired
  4. private StringRedisTemplate redisTemplate;
  5. @Autowired
  6. private JmsMessagingTemplate jmsMessagingTemplate;
  7. //1. 生成验证码并发送消息
  8. @Override
  9. public void getCode(String phone) {
  10. //1.1 生成六位数的验证码
  11. String code = (long) (Math.random()*1000000)+"";
  12. System.out.println("验证码:"+code);
  13. //1.2 将验证码存放到redis中
  14. redisTemplate.opsForValue().set(phone,code,200, TimeUnit.MINUTES);
  15. //1.3 将验证码信息发送给springboot-sms-service这个工程(它将监听我们发的信息)
  16. //1.3.1 重新组织数据(阿里云后台需要两个参数:手机号,验证号)
  17. Map<String,String> params = new HashMap<>();
  18. params.put("phone",phone);
  19. params.put("code",code);
  20. //1.3.2 将手机号及验证码发送出去
  21. jmsMessagingTemplate.convertAndSend("sms", params);
  22. }
  23. }

三、定义短信服务的监听方springboot-sms-service

3.1 添加依赖:

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.alibaba</groupId>
  8. <artifactId>fastjson</artifactId>
  9. <version>1.2.15</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.apache.httpcomponents</groupId>
  13. <artifactId>httpclient</artifactId>
  14. <version>4.2.1</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.apache.httpcomponents</groupId>
  18. <artifactId>httpcore</artifactId>
  19. <version>4.2.1</version>
  20. </dependency>
  21. <dependency>
  22. <groupId>commons-lang</groupId>
  23. <artifactId>commons-lang</artifactId>
  24. <version>2.6</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.eclipse.jetty</groupId>
  28. <artifactId>jetty-util</artifactId>
  29. <version>9.3.7.v20160115</version>
  30. </dependency>
  31. <dependency>
  32. <groupId>junit</groupId>
  33. <artifactId>junit</artifactId>
  34. <version>4.5</version>
  35. <scope>test</scope>
  36. </dependency>
  37. <dependency>
  38. <groupId>org.springframework.boot</groupId>
  39. <artifactId>spring-boot-starter-activemq</artifactId>
  40. </dependency>
  41. </dependencies>
  42. </project>

3.2 引入工具类HttpUtils,用于发送http请求:

  1. public class HttpUtils {
  2. /**
  3. * get
  4. *
  5. * @param host
  6. * @param path
  7. * @param method
  8. * @param headers
  9. * @param querys
  10. * @return
  11. * @throws Exception
  12. */
  13. public static HttpResponse doGet(String host, String path, String method,
  14. Map<String, String> headers,
  15. Map<String, String> querys)
  16. throws Exception {
  17. HttpClient httpClient = wrapClient(host);
  18. HttpGet request = new HttpGet(buildUrl(host, path, querys));
  19. for (Map.Entry<String, String> e : headers.entrySet()) {
  20. request.addHeader(e.getKey(), e.getValue());
  21. }
  22. return httpClient.execute(request);
  23. }
  24. /**
  25. * post form
  26. *
  27. * @param host
  28. * @param path
  29. * @param method
  30. * @param headers
  31. * @param querys
  32. * @param bodys
  33. * @return
  34. * @throws Exception
  35. */
  36. public static HttpResponse doPost(String host, String path, String method,
  37. Map<String, String> headers,
  38. Map<String, String> querys,
  39. Map<String, String> bodys)
  40. throws Exception {
  41. HttpClient httpClient = wrapClient(host);
  42. HttpPost request = new HttpPost(buildUrl(host, path, querys));
  43. for (Map.Entry<String, String> e : headers.entrySet()) {
  44. request.addHeader(e.getKey(), e.getValue());
  45. }
  46. if (bodys != null) {
  47. List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
  48. for (String key : bodys.keySet()) {
  49. nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
  50. }
  51. UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
  52. formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
  53. request.setEntity(formEntity);
  54. }
  55. return httpClient.execute(request);
  56. }
  57. /**
  58. * Post String
  59. *
  60. * @param host
  61. * @param path
  62. * @param method
  63. * @param headers
  64. * @param querys
  65. * @param body
  66. * @return
  67. * @throws Exception
  68. */
  69. public static HttpResponse doPost(String host, String path, String method,
  70. Map<String, String> headers,
  71. Map<String, String> querys,
  72. String body)
  73. throws Exception {
  74. HttpClient httpClient = wrapClient(host);
  75. HttpPost request = new HttpPost(buildUrl(host, path, querys));
  76. for (Map.Entry<String, String> e : headers.entrySet()) {
  77. request.addHeader(e.getKey(), e.getValue());
  78. }
  79. if (StringUtils.isNotBlank(body)) {
  80. request.setEntity(new StringEntity(body, "utf-8"));
  81. }
  82. return httpClient.execute(request);
  83. }
  84. /**
  85. * Post stream
  86. *
  87. * @param host
  88. * @param path
  89. * @param method
  90. * @param headers
  91. * @param querys
  92. * @param body
  93. * @return
  94. * @throws Exception
  95. */
  96. public static HttpResponse doPost(String host, String path, String method,
  97. Map<String, String> headers,
  98. Map<String, String> querys,
  99. byte[] body)
  100. throws Exception {
  101. HttpClient httpClient = wrapClient(host);
  102. HttpPost request = new HttpPost(buildUrl(host, path, querys));
  103. for (Map.Entry<String, String> e : headers.entrySet()) {
  104. request.addHeader(e.getKey(), e.getValue());
  105. }
  106. if (body != null) {
  107. request.setEntity(new ByteArrayEntity(body));
  108. }
  109. return httpClient.execute(request);
  110. }
  111. /**
  112. * Put String
  113. * @param host
  114. * @param path
  115. * @param method
  116. * @param headers
  117. * @param querys
  118. * @param body
  119. * @return
  120. * @throws Exception
  121. */
  122. public static HttpResponse doPut(String host, String path, String method,
  123. Map<String, String> headers,
  124. Map<String, String> querys,
  125. String body)
  126. throws Exception {
  127. HttpClient httpClient = wrapClient(host);
  128. HttpPut request = new HttpPut(buildUrl(host, path, querys));
  129. for (Map.Entry<String, String> e : headers.entrySet()) {
  130. request.addHeader(e.getKey(), e.getValue());
  131. }
  132. if (StringUtils.isNotBlank(body)) {
  133. request.setEntity(new StringEntity(body, "utf-8"));
  134. }
  135. return httpClient.execute(request);
  136. }
  137. /**
  138. * Put stream
  139. * @param host
  140. * @param path
  141. * @param method
  142. * @param headers
  143. * @param querys
  144. * @param body
  145. * @return
  146. * @throws Exception
  147. */
  148. public static HttpResponse doPut(String host, String path, String method,
  149. Map<String, String> headers,
  150. Map<String, String> querys,
  151. byte[] body)
  152. throws Exception {
  153. HttpClient httpClient = wrapClient(host);
  154. HttpPut request = new HttpPut(buildUrl(host, path, querys));
  155. for (Map.Entry<String, String> e : headers.entrySet()) {
  156. request.addHeader(e.getKey(), e.getValue());
  157. }
  158. if (body != null) {
  159. request.setEntity(new ByteArrayEntity(body));
  160. }
  161. return httpClient.execute(request);
  162. }
  163. /**
  164. * Delete
  165. *
  166. * @param host
  167. * @param path
  168. * @param method
  169. * @param headers
  170. * @param querys
  171. * @return
  172. * @throws Exception
  173. */
  174. public static HttpResponse doDelete(String host, String path, String method,
  175. Map<String, String> headers,
  176. Map<String, String> querys)
  177. throws Exception {
  178. HttpClient httpClient = wrapClient(host);
  179. HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
  180. for (Map.Entry<String, String> e : headers.entrySet()) {
  181. request.addHeader(e.getKey(), e.getValue());
  182. }
  183. return httpClient.execute(request);
  184. }
  185. private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
  186. StringBuilder sbUrl = new StringBuilder();
  187. sbUrl.append(host);
  188. if (!StringUtils.isBlank(path)) {
  189. sbUrl.append(path);
  190. }
  191. if (null != querys) {
  192. StringBuilder sbQuery = new StringBuilder();
  193. for (Map.Entry<String, String> query : querys.entrySet()) {
  194. if (0 < sbQuery.length()) {
  195. sbQuery.append("&");
  196. }
  197. if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
  198. sbQuery.append(query.getValue());
  199. }
  200. if (!StringUtils.isBlank(query.getKey())) {
  201. sbQuery.append(query.getKey());
  202. if (!StringUtils.isBlank(query.getValue())) {
  203. sbQuery.append("=");
  204. sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
  205. }
  206. }
  207. }
  208. if (0 < sbQuery.length()) {
  209. sbUrl.append("?").append(sbQuery);
  210. }
  211. }
  212. return sbUrl.toString();
  213. }
  214. private static HttpClient wrapClient(String host) {
  215. HttpClient httpClient = new DefaultHttpClient();
  216. if (host.startsWith("https://")) {
  217. sslClient(httpClient);
  218. }
  219. return httpClient;
  220. }
  221. private static void sslClient(HttpClient httpClient) {
  222. try {
  223. SSLContext ctx = SSLContext.getInstance("TLS");
  224. X509TrustManager tm = new X509TrustManager() {
  225. public X509Certificate[] getAcceptedIssuers() {
  226. return null;
  227. }
  228. public void checkClientTrusted(X509Certificate[] xcs, String str) {
  229. }
  230. public void checkServerTrusted(X509Certificate[] xcs, String str) {
  231. }
  232. };
  233. ctx.init(null, new TrustManager[] { tm }, null);
  234. SSLSocketFactory ssf = new SSLSocketFactory(ctx);
  235. ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  236. ClientConnectionManager ccm = httpClient.getConnectionManager();
  237. SchemeRegistry registry = ccm.getSchemeRegistry();
  238. registry.register(new Scheme("https", 443, ssf));
  239. } catch (KeyManagementException ex) {
  240. throw new RuntimeException(ex);
  241. } catch (NoSuchAlgorithmException ex) {
  242. throw new RuntimeException(ex);
  243. }
  244. }
  245. }

3.3 监听我们发送的消息

  1. /**
  2. * ------------------------------
  3. * 功能:
  4. * 作者:WF
  5. * 微信:hbxfwf13590332912
  6. * 创建时间:2021/8/10-16:37
  7. * ------------------------------
  8. */
  9. @Component
  10. public class MyMessageListener {
  11. @JmsListener(destination = "sms")
  12. public void getMessage(Map<String,String> params){
  13. //1. 获取手机号
  14. String phone = params.get("phone");
  15. //2. 获取验证码
  16. String code = params.get("code");
  17. System.out.println("code = " + code);
  18. //3. 使用工具类发送信息给阿里云
  19. sendMessage(phone,code);
  20. }
  21. private void sendMessage(String phone,String code){
  22. String host = "http://dingxin.market.alicloudapi.com";
  23. String path = "/dx/sendSms";
  24. String method = "POST";
  25. String appcode = "7ba36df9be9e4518bda04ba2702b8fb0";
  26. Map<String, String> headers = new HashMap<String, String>();
  27. //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
  28. headers.put("Authorization", "APPCODE " + appcode);
  29. Map<String, String> querys = new HashMap<String, String>();
  30. querys.put("mobile",phone);
  31. querys.put("param", "code:" + code);
  32. querys.put("tpl_id", "TP1711063");
  33. Map<String, String> bodys = new HashMap<String, String>();
  34. try {
  35. /**
  36. * 重要提示如下:
  37. * HttpUtils请从
  38. * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
  39. * 下载
  40. *
  41. * 相应的依赖请参照
  42. * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
  43. */
  44. HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
  45. System.out.println(response.toString());
  46. //获取response的body
  47. //System.out.println(EntityUtils.toString(response.getEntity()));
  48. } catch (Exception e) {
  49. e.printStackTrace();
  50. }
  51. }
  52. }

3.4 前端页面编写:

3.4.1 在docker下nginx服务器中配置user静态资源:

image.png

3.4.2 配置nginx服务器:

第1步:在/mydata/nginx/conf/nginx.conf下添加上服务器:

  1. upstream user{
  2. server 192.168.56.1:9005;
  3. }

第2步:在/mydata/nginx/conf/conf.d/zeyigou.conf配置自己的反向代理服务器

  1. server {
  2. listen 80;
  3. server_name user.zeyigou.com;
  4. location / {
  5. proxy_pass http://user;
  6. proxy_set_header Host $host:$server_port;
  7. }
  8. include /etc/nginx/static.conf;
  9. }

第3步:重启nginx服务器:

  1. docker restart nginx

第4步:修改zyg-user-web中的静态页面,将其中的静态路径前添加:/static/user/
第5步:在swithHost中配置域名服务器:
image.png

四、注册用户:

4.1 在前端register.html中提交表单 :

image.png

4.2 在zyg-user-web中添加注册方法:

  1. //3. 添加用户
  2. @RequestMapping("user/add")
  3. public String add(UserEntity userEntity,String validCode){
  4. //3.1 比较用户输入的验证码与redis中的验证码是否一致
  5. boolean b = userService.purdgeCode(validCode,userEntity.getPhone());
  6. //3.2 如果比较相等,就添加用户
  7. if(b){
  8. userService.add(userEntity);
  9. }
  10. return "register";
  11. }

4.3 在zyg-user-service模块完成验证码比较及用户添加

  1. /**
  2. * 功能: 比较验证码是否相等
  3. * 参数:
  4. * 返回值: boolean
  5. * 时间: 2021/8/11 14:32
  6. */
  7. @Override
  8. public boolean purdgeCode(String validCode, String phone) {
  9. //1. 根据手机号得到原来的验证码
  10. String code = redisTemplate.opsForValue().get(phone);
  11. //2. 判断是否存在
  12. if(StringUtils.isNotBlank(validCode) && StringUtils.isNotBlank(code) && validCode.equals(code)){
  13. return true;
  14. }
  15. return false;
  16. }
  17. /**
  18. * 功能: 注册新用户
  19. * 参数:
  20. * 返回值: void
  21. * 时间: 2021/8/11 14:33
  22. */
  23. @Override
  24. public void add(UserEntity userEntity) {
  25. userEntity.setCreated(new Date());
  26. userEntity.setStatus("y");
  27. //1. 将原来的密码进行加密
  28. BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
  29. String pwd = encoder.encode(userEntity.getPassword());
  30. //2. 重新保存到数据库中
  31. userEntity.setPassword(pwd);
  32. this.save(userEntity);
  33. }

4.4 数据库中查看添加的用户结果 :

image.png