阿里云实现amqp

在这里插入代码片<?php
namespace app\api\controller;

use library\Controller;
use Stomp\Client;
use Stomp\Exception\StompException;
use Stomp\Network\Observer\Exception\HeartbeatException;
use Stomp\Network\Observer\ServerAliveObserver;
use Stomp\StatefulStomp;
use Exception;
use think\Db;
use think\worker\Server;

class Subscribe extends Controller
{
//参数说明,请参见AMQP客户端接入说明文档。
public $accessKey = “”;
public $accessSecret = “”;
//消费组id 在对应实例的消息转发 > 服务端订阅 > 消费组列表查看您的消费组ID
public $consumerGroupId = “”;
public $clientId = “”;
//iotInstanceId:实例ID。
public $iotInstanceId = “”;
public $timeStamp = ‘’;
//签名方法:支持hmacmd5,hmacsha1和hmacsha256。
public $signMethod = “hmacsha1”;

public function initialize()
{
    $this->accessKey = sysconf('storage_oss_keyid');
    $this->accessSecret = sysconf('storage_oss_secret');
    $this->timeStamp = round(microtime(true) * 1000);
    $this->iotInstanceId = sysconf('storage_aliyun_iotInstanceId');
    $this->consumerGroupId = sysconf('storage_aliyun_consumerGroupId');
    $this->clientId = $this->uuid();
    $this->hostUrl = ""; //按阿里云文档拼接url
}
public function sub()
{
    $client  = $this->createClient();
    try {
        $client->connect();
    } catch (StompException $e) {
        echo "failed to connect to server, msg:" . $e->getMessage(), PHP_EOL;
    }
    //无异常时继续执行。
    $stomp = new StatefulStomp($client);
    //查询设备,根据设备拼装topic
    $stomp->subscribe("/topic/#");
    echo "connect success";
    while (true) {
        try {
            // 检查连接状态
            if (!$client->isConnected()) {
                echo "connection not exists, will reconnect after 10s.", PHP_EOL;
                sleep(10);
                //需要重新创建连接,官方给出的$client->connect()会报错
                $client  = $this->createClient();
                $stomp = new StatefulStomp($client);
                $stomp->subscribe("/topic/#");
                echo "connect success", PHP_EOL;
            }
            //处理消息业务逻辑。会监听到所有的topic,根据topic来处理数据
            $msg = $stomp->read();
            $headers = $msg->getHeaders();
            $readBody = $msg->getBody();
            $this->doBusiness($headers,$readBody);

        } catch (HeartbeatException $e) {
            echo 'The server failed to send us heartbeats within the defined interval.', PHP_EOL;
            $stomp->getClient()->disconnect();
        } catch (Exception $e) {
            echo 'process message occurs error: ' . $e->getMessage(), PHP_EOL;
            $stomp->getClient()->disconnect();
        }
    }
}





private function createClient()
{
    $userName = $this->clientId . "|authMode=aksign"
        . ",signMethod=" . $this->signMethod
        . ",timestamp=" . $this->timeStamp
        . ",authId=" . $this->accessKey
        . ",iotInstanceId=" . $this->iotInstanceId
        . ",consumerGroupId=" . $this->consumerGroupId
        . "|";
    $signContent = "authId=" . $this->accessKey . "&timestamp=" . $this->timeStamp;
    //计算签名,password组装方法,请参见AMQP客户端接入说明文档。
    $password = base64_encode(hash_hmac("sha1", $signContent, $this->accessSecret, $raw_output = TRUE));
    //接入域名,url请参见AMQP客户端接入说明文档。
    $client = new Client('ssl://url:61614');
    $sslContext = ['ssl' => ['verify_peer' => true, 'verify_peer_name' => false],];
    $client->getConnection()->setContext($sslContext);

    //服务端心跳监听。
    $observer = new ServerAliveObserver();
    $client->getConnection()->getObservers()->addObserver($observer);
    //心跳设置,需要云端每30s发送一次心跳包。
    $client->setHeartbeat(0, 30000);
    $client->setLogin($userName, $password);
    return $client;
}

public function  uuid()
{
    $chars = md5(uniqid(mt_rand(), true));
    $uuid = substr ( $chars, 0, 8 ) . '-'
        . substr ( $chars, 8, 4 ) . '-'
        . substr ( $chars, 12, 4 ) . '-'
        . substr ( $chars, 16, 4 ) . '-'
        . substr ( $chars, 20, 12 );
    return $uuid ;
}

}

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
AMQP(Advanced Message Queuing Protocol)是一种高级消息队列协议,用于在应用程序之间传递消息。阿里云提供了AMQP的Java SDK,使得Java应用程序可以轻松地与阿里云的消息队列服务(MQ)进行通信。 以下是使用阿里云AMQP Java SDK进行消息队列操作的基本步骤: 1. 引入AMQP Java SDK依赖 ```xml <dependency> <groupId>com.aliyun</groupId> <artifactId>ons-client</artifactId> <version>1.12.3</version> </dependency> ``` 2. 创建阿里云MQ实例 ```java Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.ProducerId, producerId); properties.setProperty(PropertyKeyConst.AccessKey, accessKey); properties.setProperty(PropertyKeyConst.SecretKey, secretKey); properties.setProperty(PropertyKeyConst.ONSAddr, onsAddr); Producer producer = ONSFactory.createProducer(properties); producer.start(); ``` 3. 发送消息 ```java Message message = new Message(topic, tag, body.getBytes()); SendResult sendResult = producer.send(message); ``` 4. 接收消息 ```java Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.ConsumerId, consumerId); properties.setProperty(PropertyKeyConst.AccessKey, accessKey); properties.setProperty(PropertyKeyConst.SecretKey, secretKey); properties.setProperty(PropertyKeyConst.ONSAddr, onsAddr); Consumer consumer = ONSFactory.createConsumer(properties); consumer.subscribe(topic, tag, new MessageListener() { @Override public Action consume(Message message, ConsumeContext context) { String body = new String(message.getBody()); System.out.println("Received message: " + body); return Action.CommitMessage; } }); consumer.start(); ``` 以上是使用阿里云AMQP Java SDK进行消息队列操作的基本步骤。需要注意的是,生产者和消费者需要使用相同的属性(如producerId、consumerId、accessKey、secretKey、onsAddr、topic、tag等)才能正常通信。同时,阿里云还提供了更多高级功能,如事务消息、定时消息、顺序消息等。详情请参考阿里云MQ官方文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值