5.ActiveMQ入门实践笔记

主要解决高并发问题。消息发布模式。

1. 使用前打开mq服务器

-----------------------------------mq生产者配置-----------------------------------------------------------
class="org.apache.activemq.ActiveMQConnectionFactory">



       
    
    
   

       
    
    
    


         
           
    

---------------------------------------生产代码-----------------------------------------------------------------
@Autowired
@Qualifier("jmsQueueTemplate")
private JmsTemplate jmsTemplate;
jmsTemplate.send("code", new MessageCreator() {
@Override
public Message createMessage(Session session) throws JMSException {
MapMessage mapMessage = session.createMapMessage();
mapMessage.setString("telephone", model.getTelephone());
mapMessage.setString("username", model.getUsername());
mapMessage.setString("randomCode",randomCode);
return mapMessage;
}
});

--------------------------------mq消费者配置-------------------------------------------------------------------
class="org.apache.activemq.ActiveMQConnectionFactory">



 
           
    


      
    
  


    
    

-------------------------------消费代码------------------------------------
@Service("codeConsumer")
public class SmsConsumer implements MessageListener {

@Override
public void onMessage(Message message) {
    MapMessage mapMessage = (MapMessage) message;
    try {
        String telephone = mapMessage.getString("telephone");
        String randomCode = mapMessage.getString("randomCode");
        String username = mapMessage.getString("username");
        SendSmsResponse response = AliSmsUtils.sendSms(telephone, username, randomCode);
         if(response.getCode() != null && response.getCode().equals("OK")) { 
             System.out.println("发送短信成功!");
         }
    } catch (Exception e) {
        e.printStackTrace();
    }
    //在这里也可以使用消息队列发送短信
}

}

-------------------------------阿里大于发短信工具------------------------------------------------------
public class AliSmsUtils {

static final String product = "Dysmsapi";
static final String domain = "dysmsapi.aliyuncs.com";

//此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
static final String accessKeyId = "***********";
static final String accessKeySecret = "************";

public static SendSmsResponse sendSms(String telephone,String username,String randomCode) throws ClientException {

    //可自助调整超时时间
    System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
    System.setProperty("sun.net.client.defaultReadTimeout", "10000");

    //初始化acsClient,暂不支持region化
    IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
    DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
    IAcsClient acsClient = new DefaultAcsClient(profile);

    //组装请求对象-具体描述见控制台-文档部分内容
    SendSmsRequest request = new SendSmsRequest();
    //必填:待发送手机号
    request.setPhoneNumbers(telephone);
    //必填:短信签名-可在短信控制台中找到
    request.setSignName("我爱java");   
    //必填:短信模板-可在短信控制台中找到
    request.setTemplateCode("SMS_131020016");
   
    request.setTemplateParam("{\"code\":"+randomCode+"}");
    //hint 此处可能会抛出异常,注意catch
    SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

    return sendSmsResponse;
}

public static QuerySendDetailsResponse querySendDetails(String telephone,String bizId) throws ClientException {

    //可自助调整超时时间
    System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
    System.setProperty("sun.net.client.defaultReadTimeout", "10000");

    //初始化acsClient,暂不支持region化
    IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
    DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
    IAcsClient acsClient = new DefaultAcsClient(profile);

    //组装请求对象
    QuerySendDetailsRequest request = new QuerySendDetailsRequest();
    //必填-号码
    request.setPhoneNumber(telephone);
    //可选-流水号
    request.setBizId(bizId);
    //必填-发送日期 支持30天内记录查询,格式yyyyMMdd
    SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
    request.setSendDate(ft.format(new Date()));
    //必填-页大小
    request.setPageSize(10L);
    //必填-当前页码从1开始计数
    request.setCurrentPage(1L);

    //hint 此处可能会抛出异常,注意catch
    QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);

    return querySendDetailsResponse;
}

public static void main(String[] args) throws ClientException, InterruptedException {

    String telephone = "18696143109";  
    String username = "aaa";
    String randomCode = RandomStringUtils.randomNumeric(4);
    
    //发短信
    SendSmsResponse response = sendSms(telephone,username,randomCode);
    System.out.println("短信接口返回的数据----------------");
    System.out.println("Code=" + response.getCode());
    System.out.println("Message=" + response.getMessage());
    System.out.println("RequestId=" + response.getRequestId());
    System.out.println("BizId=" + response.getBizId());

    Thread.sleep(3000L);

    //查明细
    if(response.getCode() != null && response.getCode().equals("OK")) {
        QuerySendDetailsResponse querySendDetailsResponse = querySendDetails(telephone,response.getBizId());
        System.out.println("短信明细查询接口返回数据----------------");
        System.out.println("Code=" + querySendDetailsResponse.getCode());
        System.out.println("Message=" + querySendDetailsResponse.getMessage());
        int i = 0;
        for(QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse.getSmsSendDetailDTOs())
        {
            System.out.println("SmsSendDetailDTO["+i+"]:");
            System.out.println("Content=" + smsSendDetailDTO.getContent());
            System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode());
            System.out.println("OutId=" + smsSendDetailDTO.getOutId());
            System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum());
            System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate());
            System.out.println("SendDate=" + smsSendDetailDTO.getSendDate());
            System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus());
            System.out.println("Template=" + smsSendDetailDTO.getTemplateCode());
        }
        System.out.println("TotalCount=" + querySendDetailsResponse.getTotalCount());
        System.out.println("RequestId=" + querySendDetailsResponse.getRequestId());
    }

}

}
---------------------------网易发邮件工具类---------------------------------------------------------------------------
public class MailUtils {
private static String smtp_host = "smtp.163.com"; // 网易
private static String from = "vincilovfang@163.com"; // 使用当前账户
private static String username = "vincilovfang@163.com"; // 邮箱账户
private static String password = "*******"; // 邮箱授权码
//激活邮箱地址
public static String activeUrl = "http://127.0.0.1/loveCode/customer_activeMail.action";

public static void sendMail(String subject, String content, String to) {
    Properties props = new Properties();
    props.setProperty("mail.smtp.host", smtp_host);
    props.setProperty("mail.transport.protocol", "smtp");
    props.setProperty("mail.smtp.auth", "true");
    Session session = Session.getInstance(props);
    Message message = new MimeMessage(session);
    try {
        message.setFrom(new InternetAddress(from));
        message.setRecipient(RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setContent(content, "text/html;charset=utf-8");
        Transport transport = session.getTransport();
        transport.connect(smtp_host, username, password);
        transport.sendMessage(message, message.getAllRecipients());
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("邮件发送失败...");
    }
}

public static void main(String[] args) {
    sendMail("测试邮件标题", "邮件测试内容内容", "vincilovfang@163.com");     
    System.out.println("SUCCESS");
    
}

}

你可能感兴趣的