最近公司需求需要做物联网功能的东西,最后选择了aws的iot技术,由于第一次做,只能硬着头皮看这aws上的英文文档。
首先我是先百度了下发现初始化awsiot客户端全是用AWS SDK for Java1.x,然而官方却推荐AWS SDK for Java2.x,最后只能靠自己了。。。
代码如下
首先初始化awsIot客户端
package com.example.awsmqtt.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
@Component
public class CredentialsProvider implements AwsCredentialsProvider {
//你的亚马逊账户访问密钥ID
@Value("${aws.accessKey}")
private String ACCESS_KEY;
//你的亚马逊账户访问密钥内容
@Value("${aws.secretAccessKey}")
private String SECRET_ACCESS_KEY;
@Override
public AwsCredentials resolveCredentials() {
return AwsBasicCredentials.create(ACCESS_KEY, SECRET_ACCESS_KEY);
}
}
package com.example.awsmqtt.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iot.IotClient;
/**
* @Author TZQ
* @Date 2021/9/29 8:40
* @Version 1.0
*/
@Configuration
public class AwsIotConfig {
@Autowired
private CredentialsProvider credentialsProvider;
private static Logger logger = LoggerFactory.getLogger(AwsIotConfig.class);
/**
* 创建iot服务连接
*/
@Bean
public IotClient createIotService() {
IotClient awsIot = null;
try {
awsIot = IotClient.builder().region(Region.US_EAST_1).credentialsProvider(credentialsProvider).build();
} catch (Exception e) {
logger.error("IotServiceUtil.createIotService aws-iot创建连接异常", e);
}
return awsIot;
}
}
此时iot客户端已经建立成功,然后写了一个工具类专门封装了awsiot的功能