一、新建短信微服务

1、在service模块下创建子模块service-msm


image.png
2、创建controller和service代码
image.png

**3、配置application.properties

**

  1. # 服务端口
  2. server.port=8006
  3. # 服务名
  4. spring.application.name=service-msm
  5. # mysql数据库连接
  6. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  7. spring.datasource.url=jdbc:mysql://localhost:3306/guli?serverTimezone=GMT%2B8
  8. spring.datasource.username=root
  9. spring.datasource.password=root
  10. spring.redis.host=192.168.44.131
  11. spring.redis.port=6379
  12. spring.redis.database= 0
  13. spring.redis.timeout=1800000
  14. spring.redis.lettuce.pool.max-active=20
  15. spring.redis.lettuce.pool.max-wait=-1
  16. #最大阻塞等待时间(负数表示没限制)
  17. spring.redis.lettuce.pool.max-idle=5
  18. spring.redis.lettuce.pool.min-idle=0
  19. #最小空闲
  20. #返回json的全局时间格式
  21. spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
  22. spring.jackson.time-zone=GMT+8
  23. #配置mapper xml文件的路径
  24. mybatis-plus.mapper-locations=classpath:com/atguigu/cmsservice/mapper/xml/*.xml
  25. #mybatis日志
  26. mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

4、创建启动类

创建ServiceMsmApplication.java

  1. @ComponentScan({"com.atguigu"})
  2. @SpringBootApplication(exclude = DataSourceAutoConfiguration.class)//取消数据源自动配置
  3. public class ServiceMsmApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(ServiceMsmApplication.class, args);
  6. }
  7. }

二、阿里云短信服务

帮助文档:
https://help.aliyun.com/product/44282.html?spm=5176.10629532.0.0.38311cbeYzBm73

1、开通阿里云短信服务

image.png
image.png
image.png

2、添加签名管理与模板管理

(1)添加模板管理
选择 国内消息 - 模板管理 - 添加模板
image.png

点击 添加模板,进入到添加页面,输入模板信息
image.png

点击提交,等待审核,审核通过后可以使用

(2)添加签名管理
选择 国内消息 - 签名管理 - 添加签名
image.png
点击添加签名,进入添加页面,填入相关信息
注意:签名要写的有实际意义
image.png
点击提交,等待审核,审核通过后可以使
**

三、编写发送短信接口
1、在service-msm的pom中引入依赖

  1. <dependencies>
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>fastjson</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.aliyun</groupId>
  8. <artifactId>aliyun-java-sdk-core</artifactId>
  9. </dependency>
  10. </dependencies>

2、编写controller,根据手机号发送短信

@RestController
@RequestMapping("/api/msm")
@CrossOrigin //跨域
public class MsmApiController {


      @Autowired
      private MsmService msmService;


      @Autowired
      private RedisTemplate<String, String> redisTemplate;


      @GetMapping(value = "/send/{phone}")
      public R code(@PathVariable String phone) {
          String code = redisTemplate.opsForValue().get(phone);
          if(!StringUtils.isEmpty(code)) return R.ok();


          code = RandomUtil.getFourBitRandom();
          Map<String,Object> param = new HashMap<>();
          param.put("code", code);
          boolean isSend = msmService.send(phone, "SMS_180051135", param);
          if(isSend) {
              redisTemplate.opsForValue().set(phone, code,5,TimeUnit.MINUTES);
              return R.ok();
          } else {
              return R.error().message("发送短信失败");
          }
      }

}

3、编写service

@Service
public class MsmServiceImpl implements MsmService {


      /**
       * 发送短信
       */
      public boolean send(String PhoneNumbers, String templateCode, Map<String,Object> param) {


          if(StringUtils.isEmpty(PhoneNumbers)) return false;


          DefaultProfile profile =
                  DefaultProfile.getProfile("default", "LTAIq6nIPY09VROj", "FQ7UcixT9wEqMv9F35nORPqKr8XkTF");
          IAcsClient client = new DefaultAcsClient(profile);


          CommonRequest request = new CommonRequest();
          //request.setProtocol(ProtocolType.HTTPS);
          request.setMethod(MethodType.POST);
          request.setDomain("dysmsapi.aliyuncs.com");
          request.setVersion("2017-05-25");
          request.setAction("SendSms");


          request.putQueryParameter("PhoneNumbers", PhoneNumbers);
          request.putQueryParameter("SignName", "我的谷粒在线教育网站");
          request.putQueryParameter("TemplateCode", templateCode);
          request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));


          try {
              CommonResponse response = client.getCommonResponse(request);
              System.out.println(response.getData());
              return response.getHttpResponse().isSuccess();
          } catch (ServerException e) {
              e.printStackTrace();
          } catch (ClientException e) {
              e.printStackTrace();
          }
          return false;
      }

}