当前位置:网站首页>Alibaba is bigger than sending SMS (user microservice - message microservice)
Alibaba is bigger than sending SMS (user microservice - message microservice)
2022-07-03 12:33:00 【Gentle just because of you】
Alibaba is bigger than the official website
Official website process documents :
https://help.aliyun.com/document_detail/55284.html?spm=a2c4g.11186623.6.567.77f914d1QWnwjX
Log in to Alibaba : https://dayu.aliyun.com/
Go to SMS service
https://dysms.console.aliyun.com/dysms.htm?spm=5176.12818093.0.ddysms.6eac16d0SKkGSC#/domestic/text/template
Set signature template ( Need to be reviewed )
Get AccessKey
Apply for SMS template
Summarize what you need
SMS signature , SMS template id,AccessKey,AccessKey Secret,version( Version information , It's a bit of a hole ), Action(SendSms) There is another key jar package ( rely on )
User microservices
pom.xml( Message microservices are needed api---- because AliSmsModel Class in message api in )
<dependency> <groupId>com.xiaoge</groupId> <artifactId>message-api</artifactId> <version>1.0-SNAPSHOT</version> </dependency>
RedisCacheConfig( With this configuration, you must add @EnableCaching annotation , Call the cache to redis, use redis The client view will not be garbled )
package com.xiaoge.config; import org.springframework.boot.autoconfigure.cache.CacheProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.serializer.RedisSerializationContext; import org.springframework.data.redis.serializer.RedisSerializer; @Configuration public class RedisCacheConfig { // Used cache Annotations , Serialization needs to be set manually private CacheProperties cacheProperties; /** * When this configuration class is constructed , The parameters in it , There will be Spring Of ioc Containers provide * * @param cacheProperties */ public RedisCacheConfig(CacheProperties cacheProperties) { this.cacheProperties = cacheProperties; } /** * Definition Redis Serialized form of cache * In this RedisSerializer Class submitted 3 A common form of serialization * 1 java jdk Serialization ( The default form ) * 2 json jackson ( We can switch manually ) * 3 String String Serialization ( Mainly used in string storage , Not object ) Yes key It's commonly used String Serialization */ @Bean public RedisCacheConfiguration redisCacheConfiguration() { CacheProperties.Redis redisProperties = this.cacheProperties.getRedis(); RedisCacheConfiguration config = RedisCacheConfiguration .defaultCacheConfig(); config = config.serializeValuesWith( RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json())); // Cache expiration time , Generally, we set in the configuration file if (redisProperties.getTimeToLive() != null) { config = config.entryTtl(redisProperties.getTimeToLive()); } // Whether to prefix the cache if (redisProperties.getKeyPrefix() != null) { config = config.prefixKeysWith(redisProperties.getKeyPrefix()); } // Cache of null values if (!redisProperties.isCacheNullValues()) { config = config.disableCachingNullValues(); } // Ban key if (!redisProperties.isUseKeyPrefix()) { config = config.disableKeyPrefix(); } return config; } }
Start class
@SpringBootApplication @EnableEurekaClient @EnableCaching public class MemberServiceApplication { public static void main(String[] args) { SpringApplication.run(MemberServiceApplication.class, args); } }
UserController
package com.xiaoge.controller; import com.xiaoge.domain.User; import com.xiaoge.domain.UserCollection; import com.xiaoge.service.UserCollectionService; import com.xiaoge.service.UserService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.*; import java.util.Map; /** * @Classname UserController * @Date 2022/6/6 Afternoon 8:23 * @Created by xiaoge * @Description TODO */ @Api(tags = " Foreground user management interface ") @RestController @RequestMapping public class UserController { @Autowired private UserService userService; @ApiImplicitParams({ @ApiImplicitParam(name = "phoneNum", value = " User's mobile phone number , Verification Code ") }) @ApiOperation(" Modify user information ") @PostMapping("p/sms/send") public ResponseEntity<Void> bindPhoneNum(@RequestBody Map<String, String> phoneNum) { String openId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString(); userService.bindPhoneNum(openId, phoneNum); return ResponseEntity.ok().build(); } }
UserService
package com.xiaoge.service; import com.baomidou.mybatisplus.extension.service.IService; import com.xiaoge.domain.User; import java.util.Map; /** * @Classname UserService * @Date 2022/6/6 Afternoon 7:00 * @Created by xiaoge * @Description TODO */ public interface UserService extends IService<User>{ /** * The user binds the mobile number * @param openId * @param phoneNum */ Boolean bindPhoneNum(String openId, Map<String, String> phoneNum); }
UserServiceImpl
package com.xiaoge.service.impl; import com.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.xiaoge.constant.QueueConstant; import com.xiaoge.domain.User; import com.xiaoge.mapper.UserMapper; import com.xiaoge.model.AliSmsModel; import com.xiaoge.service.UserService; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.Duration; import java.util.HashMap; import java.util.Map; /** * @Classname UserServiceImpl * @Date 2022/6/6 Afternoon 7:00 * @Created by xiaoge * @Description TODO */ @Slf4j @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{ @Autowired private RabbitTemplate rabbitTemplate; @Autowired private RedisTemplate redisTemplate; /** * The user binds the mobile number * 1. Generate a code * 2. Put it in redis * 3. Set an expiration time 5min * 4. Assembly parameters * 5. Put in mq * 6. return * @param openId * @param phoneNum */ @Override public Boolean bindPhoneNum(String openId, Map<String, String> phoneNum) { String phonenum = phoneNum.get("phonenum"); // Generate verification code String code = createCode(); // Put in redis redisTemplate.opsForValue().set(phonenum, code, Duration.ofMinutes(5)); // Assembly parameters discharge mq Signature of SMS Template of SMS , The SMS code AliSmsModel aliSmsModel = new AliSmsModel(); aliSmsModel.setPhoneNumbers(phonenum); aliSmsModel.setSignName("ego Shopping Mall "); aliSmsModel.setTemplateCode("SMS_203185255"); Map<String, String> map = new HashMap<>(2); map.put("code", code); aliSmsModel.setTemplateParam(JSON.toJSONString(map)); // Send a message rabbitTemplate.convertAndSend(QueueConstant.PHONE_CHANGE_EX, QueueConstant.PHONE_CHANGE_KEY, JSON.toJSONString(aliSmsModel)); return true; } /** * Generate verification code * @return */ private String createCode() { // digit 4 6 8 A little more // Generate verification code randomly return "88888888"; } }
Message microservices
message-api Model class in User microservices use this model class
package com.whsxt.model; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor @Builder @ApiModel(" Send entity classes with Alibaba larger than SMS ") public class AliSmsModel { @ApiModelProperty(" cell-phone number ") private String phoneNumbers; @ApiModelProperty(" Signature ") private String signName; @ApiModelProperty(" Templates id") private String templateCode; @ApiModelProperty(" Parameters ") private String templateParam; @ApiModelProperty(" SMS extension code ") private String smsUpExtendCode; @ApiModelProperty(" External pipeline extension field ") private String outId; }
pom.xml
<dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>4.0.6</version> <!-- notes : If you are prompted to report an error , Upgrade the basic package version first , If you can't solve the problem, please contact technical support --> </dependency>
RabbitMQConfig( Send a text message mq To configure PHONE_CHANGE_QUEUE They are all constant values defined casually by themselves )
package com.xiaoge.config; import com.xiaoge.constant.QueueConstant; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.BindingBuilder; import org.springframework.amqp.core.DirectExchange; import org.springframework.amqp.core.Queue; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @Classname RabbitMQConfig * @Date 2022/6/25 Afternoon 2:56 * @Created by xiaoge * @Description TODO */ @Configuration public class RabbitMQConfig { /* SMS mq To configure */ @Bean public Queue phoneChangeQueue() { return new Queue(QueueConstant.PHONE_CHANGE_QUEUE); } @Bean public DirectExchange phoneChangeExchange() { return new DirectExchange(QueueConstant.PHONE_CHANGE_EX); } @Bean public Binding bind() { return BindingBuilder .bind(phoneChangeQueue()) .to(phoneChangeExchange()) .with(QueueConstant.PHONE_CHANGE_KEY); } }
application.yml
# Alibaba is bigger than SMS template sms: region-id: cn-hangzhou access-key-id: LTAIkRdZIaLMBGKw access-secret: ZPuDXJKxZ0ZNndDXlWkO8WAcZK26n7 sys-domain: dysmsapi.aliyuncs.com version: 2017-05-25
SmsProperties
package com.xiaoge.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; /** * @Classname Sms * @Date 2022/6/25 Afternoon 3:56 * @Created by xiaoge * @Description TODO */ @Data @ConfigurationProperties(prefix = "sms") public class SmsProperties { private String regionId; private String accessKeyId; private String accessSecret; private String version; }
SmsAutoConfiguration
package com.xiaoge.config; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.profile.DefaultProfile; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @Classname SmsAutoConfiguration * @Date 2022/6/25 Afternoon 4:00 * @Created by xiaoge * @Description TODO */ @Configuration @EnableConfigurationProperties(value = SmsProperties.class) public class SmsAutoConfiguration { @Autowired private SmsProperties smsProperties; /** * Initialize Alibaba's client * Ali's is not directly given to one url You can ask directly * It requires you to write a client configuration * You call the configuration of the client to send requests * * @return */ @Bean public IAcsClient iAcsClient() { DefaultProfile profile = DefaultProfile.getProfile(smsProperties.getRegionId(), smsProperties.getAccessKeyId(), smsProperties.getAccessSecret() ); IAcsClient acsClient = new DefaultAcsClient(profile); return acsClient; } }
SmsListener( Monitor , And send text messages )
package com.xiaoge.listener; import com.alibaba.fastjson.JSON; import com.aliyuncs.CommonRequest; import com.aliyuncs.CommonResponse; import com.aliyuncs.IAcsClient; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.http.MethodType; import com.rabbitmq.client.Channel; import com.xiaoge.config.SmsProperties; import com.xiaoge.constant.QueueConstant; import com.xiaoge.model.AliSmsModel; import com.xiaoge.service.SmsLogService; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * @Classname SmsListener * @Date 2022/6/25 Afternoon 3:52 * @Created by xiaoge * @Description TODO */ @Component @Slf4j public class SmsListener { @Autowired private SmsProperties smsProperties; @Autowired private IAcsClient iAcsClient; @Autowired private SmsLogService smsLogService; /** * SMS monitoring concurrency Number of threads 3-5 individual */ @RabbitListener(queues = QueueConstant.PHONE_CHANGE_QUEUE, concurrency = "3-5") public void smsHandler(Message message, Channel channel){ // Get the news String msg = new String(message.getBody()); // What to send AliSmsModel aliSmsModel = JSON.parseObject(msg, AliSmsModel.class); // I'm texting try { CommonResponse commonResponse = realSendMsg(aliSmsModel); // succeed log.info(" Message sent successfully "); // Record database smsLogService.saveMsg(aliSmsModel, commonResponse); // Sign for channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); } catch (Exception e) { log.error(" Failed to send SMS "); } } /** * Send a text message * @param aliSmsModel * @return */ private CommonResponse realSendMsg(AliSmsModel aliSmsModel) throws ClientException { CommonRequest commonRequest = new CommonRequest(); // The basic parameters commonRequest.setVersion(smsProperties.getVersion()); commonRequest.setMethod(MethodType.POST); commonRequest.setRegionId(smsProperties.getRegionId()); commonRequest.setAction("SendSms"); commonRequest.setDomain("dysmsapi.aliyuncs.com"); // To which mobile number commonRequest.putQueryParameter("PhoneNumbers", aliSmsModel.getPhoneNumbers()); commonRequest.putQueryParameter("SignName", aliSmsModel.getSignName()); commonRequest.putQueryParameter("TemplateCode", aliSmsModel.getTemplateCode()); commonRequest.putQueryParameter("TemplateParam", aliSmsModel.getTemplateParam()); // Send the request CommonResponse commonResponse = iAcsClient.getCommonResponse(commonRequest); System.out.println(commonResponse.getData()); System.out.println(commonResponse.getHttpStatus()); return commonResponse; } }
SmsLogService
package com.xiaoge.service; import com.aliyuncs.CommonResponse; import com.baomidou.mybatisplus.extension.service.IService; import com.xiaoge.domain.SmsLog; import com.xiaoge.model.AliSmsModel; /** * @Classname SmsLogService * @Date 2022/6/25 Afternoon 3:19 * @Created by xiaoge * @Description TODO */ public interface SmsLogService extends IService<SmsLog>{ /** * Save the SMS information into the database * @param aliSmsModel * @param commonResponse */ void saveMsg(AliSmsModel aliSmsModel, CommonResponse commonResponse); }
SmsLogServiceImpl( Save the sent SMS to the database )
package com.xiaoge.service.impl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.aliyuncs.CommonResponse; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.xiaoge.domain.SmsLog; import com.xiaoge.mapper.SmsLogMapper; import com.xiaoge.model.AliSmsModel; import com.xiaoge.service.SmsLogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; /** * @Classname SmsLogServiceImpl * @Date 2022/6/25 Afternoon 3:19 * @Created by xiaoge * @Description TODO */ @Service public class SmsLogServiceImpl extends ServiceImpl<SmsLogMapper, SmsLog> implements SmsLogService{ @Autowired private SmsLogMapper smsLogMapper; /** * Save the SMS information into the database * * @param aliSmsModel * @param commonResponse */ @Override public void saveMsg(AliSmsModel aliSmsModel, CommonResponse commonResponse) { String phoneNumbers = aliSmsModel.getPhoneNumbers(); String templateParam = aliSmsModel.getTemplateParam(); JSONObject jsonObject = JSON.parseObject(templateParam); String code = jsonObject.getString("code"); SmsLog smsLog = new SmsLog(); smsLog.setUserPhone(phoneNumbers); smsLog.setContent(" Dear users , Your registered member dynamic password is :" + code + ", Don't let it out to others !"); smsLog.setMobileCode(code); smsLog.setRecDate(new Date()); String data = commonResponse.getData(); JSONObject jsonObject1 = JSON.parseObject(data); String code1 = jsonObject1.getString("Code"); smsLog.setResponseCode(String.valueOf(commonResponse.getHttpStatus())); if (code1.equals("OK")) { smsLog.setStatus(1); } else { smsLog.setStatus(0); } smsLog.setType(2); // Insert database smsLogMapper.insert(smsLog); } }
边栏推荐
- 2.7 overview of livedata knowledge points
- Eureka自我保护
- Computer version wechat applet full screen display method, mobile phone horizontal screen method.
- Integer int compare size
- PHP export word method (phpword)
- Dart: about grpc (I)
- Dart: about Libraries
- Lambda expression
- Adult adult adult
- 手机号码变成空号导致亚马逊账号登陆两步验证失败的恢复网址及方法
猜你喜欢
剑指Offer04. 二维数组中的查找【中等】
Basic knowledge of OpenGL (sort it out according to your own understanding)
Shutter widget: centerslice attribute
TOGAF认证自学宝典V2.0
Integer string int mutual conversion
Use bloc to build a page instance of shutter
Itext7 uses iexternalsignature container for signature and signature verification
剑指Offer07. 重建二叉树
Sword finger offer09 Implementing queues with two stacks
Shutter: overview of shutter architecture (excerpt)
随机推荐
剑指Offer03. 数组中重复的数字【简单】
Fluent: Engine Architecture
Atomic atomic operation
云计算未来 — 云原生
Dart: view the dill compiled code file
Capturing and sorting out external Fiddler -- Conversation bar and filter [2]
Integer string int mutual conversion
【附下载】密码获取工具LaZagne安装及使用
Is it OK to open an account for online stock speculation? Is the fund safe?
QT OpenGL rotate, pan, zoom
在网上炒股开户可以吗?资金安全吗?
idea将web项目打包成war包并部署到服务器上运行
[combinatorics] permutation and combination (summary of permutation and combination content | selection problem | set permutation | set combination)
[embedded] - Introduction to four memory areas
Redis
[MySQL special] read lock and write lock
OpenGL shader use
[ManageEngine] the role of IP address scanning
Unicode查询的官方网站
(database authorization - redis) summary of unauthorized access vulnerabilities in redis