1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import com.aliyun.dysmsapi20170525.Client; import com.aliyun.dysmsapi20170525.models.SendSmsRequest; import com.aliyun.teaopenapi.models.Config; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit;
@Service public class SmsService { private static final long REDIS_EXPIRE_SECONDS = 60; private static final long BLOCK_TIMEOUT_SECONDS = 30;
@Autowired private StringRedisTemplate redisTemplate; @Autowired private Client smsClient;
public String sendSmsSync(String phone, String templateCode, String templateParam) { String requestId = UUID.randomUUID().toString().replace("-", ""); String statusKey = "sms:status:" + requestId; String latchKey = "sms:latch:" + requestId;
try { CountDownLatch latch = new CountDownLatch(1); redisTemplate.opsForValue().set(statusKey, "WAITING", REDIS_EXPIRE_SECONDS, TimeUnit.SECONDS); redisTemplate.opsForValue().set(latchKey, latch.toString(), REDIS_EXPIRE_SECONDS, TimeUnit.SECONDS);
SendSmsRequest smsRequest = new SendSmsRequest() .setPhoneNumbers(phone) .setTemplateCode(templateCode) .setTemplateParam(templateParam) .setOutId(requestId); smsClient.sendSms(smsRequest);
boolean isSuccess = latch.await(BLOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS); if (!isSuccess) { redisTemplate.opsForValue().set(statusKey, "TIMEOUT", REDIS_EXPIRE_SECONDS, TimeUnit.SECONDS); return "TIMEOUT"; }
String finalStatus = redisTemplate.opsForValue().get(statusKey); return finalStatus != null ? finalStatus : "UNKNOWN";
} catch (Exception e) { redisTemplate.opsForValue().set(statusKey, "FAIL", REDIS_EXPIRE_SECONDS, TimeUnit.SECONDS); return "FAIL"; } finally { redisTemplate.delete(statusKey); redisTemplate.delete(latchKey); } }
public void handleSmsCallback(String requestId, String status) { String statusKey = "sms:status:" + requestId; String latchKey = "sms:latch:" + requestId;
try { redisTemplate.opsForValue().set(statusKey, status, REDIS_EXPIRE_SECONDS, TimeUnit.SECONDS); CountDownLatch latch = (CountDownLatch) redisTemplate.opsForValue().get(latchKey); if (latch != null) { latch.countDown(); } } catch (Exception e) { } }
public static Client createSmsClient() throws Exception { Config config = new Config() .setAccessKeyId("your-access-key-id") .setAccessKeySecret("your-access-key-secret"); config.endpoint = "dysmsapi.aliyuncs.com"; return new Client(config); } }
|