转载于:http://www.architecy.com/archives/483

阿里mns支持普通服务的消息服务,也就是对数据量较小的服务。

MNS支持两种操作类型,队列和主题,也可以是队列和主题的柔和

下面是前期使用测试的一个流程图,具体使用的是对列和主题的结合

 

pom.xml

        <!-- 阿里mns 客户端 -->
        <dependency>
            <groupId>com.aliyun.mns</groupId>
            <artifactId>aliyun-sdk-mns</artifactId>
            <version>1.1.8</version>
            <classifier>jar-with-dependencies</classifier>
        </dependency>

 

application-local.yml

#mns配置
auth:
  mns:
    id: LTAI9auC0WRljjTjabdjdojg
    secret: Xr3PkMWR55xvZ9Mrk4fIYPyWjnAajZdddggd
    endpoint: http://31373024.mns.cn-beijing.aliyuncs.com/
    connectTime: 3000
    socketTime: 3000

MnsConfig.java

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;


@Data
@Component
@RefreshScope
@ConfigurationProperties(prefix = "auth.mns")
public class MnsConfig {

    private String id;

    private String secret;

    private String endpoint;

    private int connectTime;

    private int socketTime;
}

MnsTopic.java

import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudTopic;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.common.ClientException;
import com.aliyun.mns.common.ServiceException;
import com.aliyun.mns.common.http.ClientConfiguration;
import com.aliyun.mns.model.TopicMessage;
import javafx.util.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@RefreshScope
@Component
public class MnsTopic {
    private static Logger logger = LoggerFactory.getLogger(MnsTopic.class);

    private static final String TOPIC_NAME = "test-dev";
    /** success */
    private static final int RESULT_SUCCESS = 0;

    private static final int RESULT_FAIL = -1;

    private MNSClient client;

    @Autowired
    private MnsConfig mnsConfig;




    @PostConstruct
    public void init(){
        ClientConfiguration configuration = new ClientConfiguration();
        configuration.setConnectionTimeout(mnsConfig.getConnectTime());
        configuration.setSocketTimeout(mnsConfig.getSocketTime());
        logger.info("MnsTopic init  endpoint={}", mnsConfig.getEndpoint());
        logger.info("MnsTopic init  id={}", mnsConfig.getId());
        logger.info("MnsTopic init  secret={}", mnsConfig.getSecret());
        CloudAccount account = new CloudAccount(
                mnsConfig.getId(),
                mnsConfig.getSecret(),
                mnsConfig.getEndpoint(), configuration);
        client = account.getMNSClient();
    }

    /**
     * 消息生产逻辑
     *
     * @param message
     * @return <code,msg>; code:0成功-1失败; msg:成功为messageId失败为失败原因
     */
    public Pair<Integer, String> publish(TopicMessage message) {
        String msg = "";
        int code = RESULT_FAIL;
        do {
            if (message == null) {
                msg = "msg is null";
                break;
            }
            String body = message.getMessageBody();
            if (body == null || body.trim().length() == 0) {
                msg = "msg's body is empty";
                break;
            }
            try {
                CloudTopic topic = client.getTopicRef(TOPIC_NAME);
                TopicMessage result = topic.publishMessage(message);
                code = RESULT_SUCCESS;
                msg = result.getMessageId();
            } catch (ClientException ce) {
                msg = "mns client exception : " + ce.toString();
            } catch (ServiceException se) {
                msg = "mns server exception : " + se.toString();
            } catch (Exception e) {
                msg = "mns unknown exception happened!: " + e.getMessage();
            } finally {
                break;
            }
        } while (true);
        if (logger.isDebugEnabled()){
            logger.debug("MnsTopic.publish()|{}|{}", code, msg);
        }
        return new Pair<>(code, msg);
    }

    public static void main(String[] args) {

        TopicMessage message = new TopicMessage() {
            @Override
            public String getMessageBody() {
                return "要发送的消息内容";
            }
        };
        MnsTopic mnsTopic = new MnsTopic();
        mnsTopic.publish(message);
    }
}

结束。