当前位置:网站首页>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
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-85JBDKAv-1656147205975)(/Users/xiaoge/Downloads/assests/image-20220625163030313.png)]](/img/be/650f07a569fa556844ee264614d1d4.png)
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 )
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-q8SDGszf-1656147205980)(/Users/xiaoge/Downloads/assests/image-20220625163303504.png)]](/img/72/cdceea16c475745ab3509d08e6ba82.png)
Get AccessKey
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-eozsw9jY-1656147205980)(/Users/xiaoge/Downloads/assests/image-20220625163329165.png)]](/img/1a/7d3d52a9fa764c794ddbdba61a0197.png)

Apply for SMS template
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-d9LeHR5N-1656147205983)(/Users/xiaoge/Downloads/assests/image-20220625163405349.png)]](/img/d6/81492fa889ccf737fda8ef2486b281.png)
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-25SmsProperties
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); } }
边栏推荐
猜你喜欢

剑指Offer10- I. 斐波那契数列
![[download attached] password acquisition tool lazagne installation and use](/img/21/eccf87ad9946d4177b600d96e17322.png)
[download attached] password acquisition tool lazagne installation and use

Take you to the installation and simple use tutorial of the deveco studio compiler of harmonyos to create and run Hello world?

Swagger

PHP export word method (one MHT)

1-2 project technology selection and structure

Itext7 uses iexternalsignature container for signature and signature verification

Use bloc to build a page instance of shutter
![[ManageEngine] the role of IP address scanning](/img/dc/df353da0e93e4d936c39a39493b508.png)
[ManageEngine] the role of IP address scanning

ES6 standard
随机推荐
If you can't learn, you have to learn. Jetpack compose writes an im app (II)
347. Top k high frequency elements
error: expected reference but got (raw string)
regular expression
New features of ES6
The future of cloud computing cloud native
Use of atomicinteger
Lambda表达式
Integer string int mutual conversion
Prompt unread messages and quantity before opening chat group
Jsup crawls Baidu Encyclopedia
JVM memory model
Adult adult adult
Introduction to concurrent programming (I)
剑指Offer03. 数组中重复的数字【简单】
flinksql是可以直接客户端建表读mysql或是kafka数据,但是怎么让它自动流转计算起来呢?
Pragma pack syntax and usage
在网上炒股开户可以吗?资金安全吗?
(construction notes) ADT and OOP
ES6 standard