本示例介绍使用Alibaba Cloud SDK for Java调用CreateRule接口对指定Topic新建一个规则。
前提条件
请在pom.xml文件中增加以下依赖,准确的SDK版本号,参见阿里云开发工具包(SDK)。
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>java.demo</groupId>
<artifactId>test</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-core -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.4.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-iot -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-iot</artifactId>
<version>6.11.0</version>
</dependency>
</dependencies>
</project>
示例代码
说明 如需启动规则,需包含ProductKey、ShortTopic、Select三个参数的信息。
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.iot.model.v20180120.CreateRuleRequest;
import com.aliyuncs.iot.model.v20180120.CreateRuleResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
/**
* 调用该接口对指定Topic新建一个规则。
*/
public class TestCreateRule {
public static void main(String[] args) {
DefaultProfile profile = DefaultProfile.getProfile(
"<your-region-id>", // 地域ID
"<your-access-key-id>", // 您的AccessKey ID
"<your-access-key-secret>"); // 您的AccessKey Secret
IAcsClient client = new DefaultAcsClient(profile);
// 创建请求接口
CreateRuleRequest request = new CreateRuleRequest();
// 应用该规则的产品Key。
request.setProductKey("yourProductKey");
// 规则名称。支持使用中英文字符、数字和下划线(_),长度应为4~30位(一个中文字符算2位)。
request.setName("测试");
// 要执行的SQL Select语句。
// 此处传入的是 Select下的内容。例如,如果 Selcet语句为 Select a,b,c,则此处传入 a,b,c。
request.setSelect("a,b,c");
// 规则的触发条件。
// 此处传入的是 Where中的内容。例如,如果 Where语句为 Where a>10,则此处传入 a>10。
request.setWhere("a>10");
// 应用该规则的具体Topic,格式为:${deviceName}/topicShortName。
// 其中,${deviceName}指具体设备的名称,topicShortName是自定义类目。
//
// 调用QueryDevice接口,查看产品下的所有设备。返回结果中包含所有的DeviceName。
// 调用QueryProductTopic接口,查看产品下的所有Topic类。返回结果中包含所有的TopicShortName。
request.setShortTopic("open_api_dev/get");
// 规则的描述信息。长度限制为100字符(一个汉字占一个字符)。
request.setRuleDesc("测试啊测试,测试啊测试,测试啊测试。");
// 规则处理的数据格式,需与待处理的设备数据格式一致。取值:
// JSON:JSON数据。
// BINARY:二进制数据。默认为:JSON
// 若选择为 BINARY, TopicType不能选择为0(系统Topic),且不能将数据转发至表格存储、时序时空数据库和云数据库RDS版。
request.setDataType("JSON");
// 0:系统Topic,
// 1:自定义Topic。
// 2:设备状态消息(Topic:/as/mqtt/status/${productKey}/${deviceName}。)
request.setTopicType(1);
try {
// 发起请求并获取返回值
CreateRuleResponse response = client.getAcsResponse(request);
// 处理业务逻辑
System.out.println(new Gson().toJson(response));
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
System.out.println("ErrCode:" + e.getErrCode());
System.out.println("ErrMsg:" + e.getErrMsg());
System.out.println("RequestId:" + e.getRequestId());
}
}
}
在文档使用中是否遇到以下问题
更多建议
匿名提交