JAVA-10628: Create new aws-modules and move other aws related modules
inside it
This commit is contained in:
+51
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.dynamodb.entity;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute;
|
||||
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey;
|
||||
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
|
||||
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
|
||||
|
||||
@DynamoDBTable(tableName = "ProductInfo")
|
||||
public class ProductInfo {
|
||||
|
||||
private String id;
|
||||
private String msrp;
|
||||
private String cost;
|
||||
|
||||
public ProductInfo() {
|
||||
}
|
||||
|
||||
public ProductInfo(String cost, String msrp) {
|
||||
this.msrp = msrp;
|
||||
this.cost = cost;
|
||||
}
|
||||
|
||||
@DynamoDBHashKey
|
||||
@DynamoDBAutoGeneratedKey
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@DynamoDBAttribute
|
||||
public String getMsrp() {
|
||||
return msrp;
|
||||
}
|
||||
|
||||
@DynamoDBAttribute
|
||||
public String getCost() {
|
||||
return cost;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public void setMsrp(String msrp) {
|
||||
this.msrp = msrp;
|
||||
}
|
||||
|
||||
public void setCost(String cost) {
|
||||
this.cost = cost;
|
||||
}
|
||||
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.dynamodb.repository;
|
||||
|
||||
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
|
||||
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBScanExpression;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.util.List;
|
||||
|
||||
public abstract class AbstractRepository<T, ID extends Serializable> {
|
||||
|
||||
protected DynamoDBMapper mapper;
|
||||
protected Class<T> entityClass;
|
||||
|
||||
protected AbstractRepository() {
|
||||
ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
|
||||
|
||||
// This entityClass refers to the actual entity class in the subclass declaration.
|
||||
|
||||
// For instance, ProductInfoDAO extends AbstractDAO<ProductInfo, String>
|
||||
// In this case entityClass = ProductInfo, and ID is String type
|
||||
// which refers to the ProductInfo's partition key string value
|
||||
this.entityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
|
||||
}
|
||||
|
||||
public void save(T t) {
|
||||
mapper.save(t);
|
||||
}
|
||||
|
||||
public T findOne(ID id) {
|
||||
return mapper.load(entityClass, id);
|
||||
}
|
||||
|
||||
/**
|
||||
* <strong>WARNING:</strong> It is not recommended to perform full table scan
|
||||
* targeting the real production environment.
|
||||
*
|
||||
* @return All items
|
||||
*/
|
||||
public List<T> findAll() {
|
||||
DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();
|
||||
return mapper.scan(entityClass, scanExpression);
|
||||
}
|
||||
|
||||
public void setMapper(DynamoDBMapper dynamoDBMapper) {
|
||||
this.mapper = dynamoDBMapper;
|
||||
}
|
||||
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.dynamodb.repository;
|
||||
|
||||
import com.baeldung.dynamodb.entity.ProductInfo;
|
||||
|
||||
public class ProductInfoRepository extends AbstractRepository<ProductInfo, String> {
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package com.baeldung.ec2;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import com.amazonaws.auth.AWSCredentials;
|
||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
||||
import com.amazonaws.auth.BasicAWSCredentials;
|
||||
import com.amazonaws.regions.Regions;
|
||||
import com.amazonaws.services.ec2.AmazonEC2;
|
||||
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
|
||||
import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
|
||||
import com.amazonaws.services.ec2.model.CreateKeyPairRequest;
|
||||
import com.amazonaws.services.ec2.model.CreateKeyPairResult;
|
||||
import com.amazonaws.services.ec2.model.CreateSecurityGroupRequest;
|
||||
import com.amazonaws.services.ec2.model.DescribeInstancesRequest;
|
||||
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
|
||||
import com.amazonaws.services.ec2.model.DescribeKeyPairsRequest;
|
||||
import com.amazonaws.services.ec2.model.DescribeKeyPairsResult;
|
||||
import com.amazonaws.services.ec2.model.IpPermission;
|
||||
import com.amazonaws.services.ec2.model.IpRange;
|
||||
import com.amazonaws.services.ec2.model.MonitorInstancesRequest;
|
||||
import com.amazonaws.services.ec2.model.RebootInstancesRequest;
|
||||
import com.amazonaws.services.ec2.model.RunInstancesRequest;
|
||||
import com.amazonaws.services.ec2.model.StartInstancesRequest;
|
||||
import com.amazonaws.services.ec2.model.StopInstancesRequest;
|
||||
import com.amazonaws.services.ec2.model.UnmonitorInstancesRequest;
|
||||
|
||||
public class EC2Application {
|
||||
|
||||
private static final AWSCredentials credentials;
|
||||
|
||||
static {
|
||||
// put your accesskey and secretkey here
|
||||
credentials = new BasicAWSCredentials(
|
||||
"<AWS accesskey>",
|
||||
"<AWS secretkey>"
|
||||
);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
// Set up the client
|
||||
AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard()
|
||||
.withCredentials(new AWSStaticCredentialsProvider(credentials))
|
||||
.withRegion(Regions.US_EAST_1)
|
||||
.build();
|
||||
|
||||
// Create a security group
|
||||
CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest().withGroupName("BaeldungSecurityGroup")
|
||||
.withDescription("Baeldung Security Group");
|
||||
ec2Client.createSecurityGroup(createSecurityGroupRequest);
|
||||
|
||||
// Allow HTTP and SSH traffic
|
||||
IpRange ipRange1 = new IpRange().withCidrIp("0.0.0.0/0");
|
||||
|
||||
IpPermission ipPermission1 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
|
||||
.withIpProtocol("tcp")
|
||||
.withFromPort(80)
|
||||
.withToPort(80);
|
||||
|
||||
IpPermission ipPermission2 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
|
||||
.withIpProtocol("tcp")
|
||||
.withFromPort(22)
|
||||
.withToPort(22);
|
||||
|
||||
AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest()
|
||||
.withGroupName("BaeldungSecurityGroup")
|
||||
.withIpPermissions(ipPermission1, ipPermission2);
|
||||
|
||||
ec2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);
|
||||
|
||||
// Create KeyPair
|
||||
CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest()
|
||||
.withKeyName("baeldung-key-pair");
|
||||
CreateKeyPairResult createKeyPairResult = ec2Client.createKeyPair(createKeyPairRequest);
|
||||
String privateKey = createKeyPairResult
|
||||
.getKeyPair()
|
||||
.getKeyMaterial(); // make sure you keep it, the private key, Amazon doesn't store the private key
|
||||
|
||||
// See what key-pairs you've got
|
||||
DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();
|
||||
DescribeKeyPairsResult describeKeyPairsResult = ec2Client.describeKeyPairs(describeKeyPairsRequest);
|
||||
|
||||
// Launch an Amazon Instance
|
||||
RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId("ami-97785bed") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html | https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/usingsharedamis-finding.html
|
||||
.withInstanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
|
||||
.withMinCount(1)
|
||||
.withMaxCount(1)
|
||||
.withKeyName("baeldung-key-pair") // optional - if not present, can't connect to instance
|
||||
.withSecurityGroups("BaeldungSecurityGroup");
|
||||
|
||||
String yourInstanceId = ec2Client.runInstances(runInstancesRequest).getReservation().getInstances().get(0).getInstanceId();
|
||||
|
||||
// Start an Instance
|
||||
StartInstancesRequest startInstancesRequest = new StartInstancesRequest()
|
||||
.withInstanceIds(yourInstanceId);
|
||||
|
||||
ec2Client.startInstances(startInstancesRequest);
|
||||
|
||||
// Monitor Instances
|
||||
MonitorInstancesRequest monitorInstancesRequest = new MonitorInstancesRequest()
|
||||
.withInstanceIds(yourInstanceId);
|
||||
|
||||
ec2Client.monitorInstances(monitorInstancesRequest);
|
||||
|
||||
UnmonitorInstancesRequest unmonitorInstancesRequest = new UnmonitorInstancesRequest()
|
||||
.withInstanceIds(yourInstanceId);
|
||||
|
||||
ec2Client.unmonitorInstances(unmonitorInstancesRequest);
|
||||
|
||||
// Reboot an Instance
|
||||
|
||||
RebootInstancesRequest rebootInstancesRequest = new RebootInstancesRequest()
|
||||
.withInstanceIds(yourInstanceId);
|
||||
|
||||
ec2Client.rebootInstances(rebootInstancesRequest);
|
||||
|
||||
// Stop an Instance
|
||||
StopInstancesRequest stopInstancesRequest = new StopInstancesRequest()
|
||||
.withInstanceIds(yourInstanceId);
|
||||
|
||||
ec2Client.stopInstances(stopInstancesRequest)
|
||||
.getStoppingInstances()
|
||||
.get(0)
|
||||
.getPreviousState()
|
||||
.getName();
|
||||
|
||||
// Describe an Instance
|
||||
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
|
||||
DescribeInstancesResult response = ec2Client.describeInstances(describeInstancesRequest);
|
||||
System.out.println(response.getReservations()
|
||||
.get(0)
|
||||
.getInstances()
|
||||
.get(0)
|
||||
.getKernelId());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package com.baeldung.rds;
|
||||
|
||||
import com.amazonaws.auth.AWSCredentialsProvider;
|
||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
||||
import com.amazonaws.auth.BasicAWSCredentials;
|
||||
import com.amazonaws.regions.Regions;
|
||||
import com.amazonaws.services.rds.AmazonRDS;
|
||||
import com.amazonaws.services.rds.AmazonRDSClientBuilder;
|
||||
import com.amazonaws.services.rds.model.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.sql.*;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import java.util.UUID;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class AWSRDSService {
|
||||
|
||||
|
||||
final static Logger logger = Logger.getLogger(AWSRDSService.class.getName());
|
||||
private AWSCredentialsProvider credentials;
|
||||
private AmazonRDS amazonRDS;
|
||||
private String db_username;
|
||||
private String db_password;
|
||||
private String db_database;
|
||||
private String db_hostname;
|
||||
|
||||
/*
|
||||
* User access key and secret key must be set before execute any operation.
|
||||
* Follow the link on how to get the user access and secret key
|
||||
* https://aws.amazon.com/blogs/security/wheres-my-secret-access-key/
|
||||
* **/
|
||||
public AWSRDSService() throws IOException {
|
||||
//Init RDS client with credentials and region.
|
||||
credentials = new
|
||||
AWSStaticCredentialsProvider(new
|
||||
BasicAWSCredentials("<ACCESS_KEY>",
|
||||
"<SECRET_KEY>"));
|
||||
amazonRDS = AmazonRDSClientBuilder.standard().withCredentials(credentials)
|
||||
.withRegion(Regions.AP_SOUTHEAST_2).build();
|
||||
Properties prop = new Properties();
|
||||
InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties");
|
||||
prop.load(input);
|
||||
db_username = prop.getProperty("db_username");
|
||||
db_password = prop.getProperty("db_password");
|
||||
db_database = prop.getProperty("db_database");
|
||||
}
|
||||
|
||||
public AWSRDSService(AmazonRDS amazonRDS){
|
||||
this.amazonRDS = amazonRDS;
|
||||
}
|
||||
|
||||
/**
|
||||
* create the RDS instance.
|
||||
* After instance creation, update the db_hostname with endpoint in db.properties.
|
||||
* */
|
||||
|
||||
public String launchInstance() {
|
||||
|
||||
String identifier = "";
|
||||
CreateDBInstanceRequest request = new CreateDBInstanceRequest();
|
||||
// RDS instance name
|
||||
request.setDBInstanceIdentifier("Sydney");
|
||||
request.setEngine("postgres");
|
||||
request.setMultiAZ(false);
|
||||
request.setMasterUsername(db_username);
|
||||
request.setMasterUserPassword(db_password);
|
||||
request.setDBName(db_database);
|
||||
request.setStorageType("gp2");
|
||||
request.setAllocatedStorage(10);
|
||||
|
||||
DBInstance instance = amazonRDS.createDBInstance(request);
|
||||
|
||||
// Information about the new RDS instance
|
||||
identifier = instance.getDBInstanceIdentifier();
|
||||
String status = instance.getDBInstanceStatus();
|
||||
Endpoint endpoint = instance.getEndpoint();
|
||||
String endpoint_url = "Endpoint URL not available yet.";
|
||||
if (endpoint != null) {
|
||||
endpoint_url = endpoint.toString();
|
||||
}
|
||||
logger.info(identifier + "\t" + status);
|
||||
logger.info(endpoint_url);
|
||||
|
||||
return identifier;
|
||||
|
||||
}
|
||||
|
||||
// Describe DB instances
|
||||
public void listInstances() {
|
||||
DescribeDBInstancesResult result = amazonRDS.describeDBInstances();
|
||||
List<DBInstance> instances = result.getDBInstances();
|
||||
for (DBInstance instance : instances) {
|
||||
// Information about each RDS instance
|
||||
String identifier = instance.getDBInstanceIdentifier();
|
||||
String engine = instance.getEngine();
|
||||
String status = instance.getDBInstanceStatus();
|
||||
Endpoint endpoint = instance.getEndpoint();
|
||||
String endpoint_url = "Endpoint URL not available yet.";
|
||||
if (endpoint != null) {
|
||||
endpoint_url = endpoint.toString();
|
||||
}
|
||||
logger.info(identifier + "\t" + engine + "\t" + status);
|
||||
logger.info("\t" + endpoint_url);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//Delete RDS instance
|
||||
public void terminateInstance(String identifier) {
|
||||
|
||||
DeleteDBInstanceRequest request = new DeleteDBInstanceRequest();
|
||||
request.setDBInstanceIdentifier(identifier);
|
||||
request.setSkipFinalSnapshot(true);
|
||||
|
||||
// Delete the RDS instance
|
||||
DBInstance instance = amazonRDS.deleteDBInstance(request);
|
||||
|
||||
// Information about the RDS instance being deleted
|
||||
String status = instance.getDBInstanceStatus();
|
||||
Endpoint endpoint = instance.getEndpoint();
|
||||
String endpoint_url = "Endpoint URL not available yet.";
|
||||
if (endpoint != null) {
|
||||
endpoint_url = endpoint.toString();
|
||||
}
|
||||
|
||||
logger.info(identifier + "\t" + status);
|
||||
logger.info(endpoint_url);
|
||||
|
||||
}
|
||||
|
||||
|
||||
public void runJdbcTests() throws SQLException, IOException {
|
||||
|
||||
// Getting database properties from db.properties
|
||||
Properties prop = new Properties();
|
||||
InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties");
|
||||
prop.load(input);
|
||||
db_hostname = prop.getProperty("db_hostname");
|
||||
String jdbc_url = "jdbc:postgresql://" + db_hostname + ":5432/" + db_database;
|
||||
|
||||
// Create a connection using the JDBC driver
|
||||
try (Connection conn = DriverManager.getConnection(jdbc_url, db_username, db_password)) {
|
||||
|
||||
// Create the test table if not exists
|
||||
Statement statement = conn.createStatement();
|
||||
String sql = "CREATE TABLE IF NOT EXISTS jdbc_test (id SERIAL PRIMARY KEY, content VARCHAR(80))";
|
||||
statement.executeUpdate(sql);
|
||||
|
||||
// Do some INSERT
|
||||
PreparedStatement preparedStatement = conn.prepareStatement("INSERT INTO jdbc_test (content) VALUES (?)");
|
||||
String content = "" + UUID.randomUUID();
|
||||
preparedStatement.setString(1, content);
|
||||
preparedStatement.executeUpdate();
|
||||
logger.info("INSERT: " + content);
|
||||
|
||||
// Do some SELECT
|
||||
sql = "SELECT * FROM jdbc_test";
|
||||
ResultSet resultSet = statement.executeQuery(sql);
|
||||
while (resultSet.next()) {
|
||||
String count = resultSet.getString("content");
|
||||
logger.info("Total Records: " + count);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException, SQLException {
|
||||
AWSRDSService awsrdsService = new AWSRDSService();
|
||||
|
||||
String instanceName = awsrdsService.launchInstance();
|
||||
|
||||
//Add some wait for instance creation.
|
||||
|
||||
awsrdsService.listInstances();
|
||||
|
||||
awsrdsService.runJdbcTests();
|
||||
|
||||
awsrdsService.terminateInstance(instanceName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package com.baeldung.sqs;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.amazonaws.auth.AWSCredentials;
|
||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
||||
import com.amazonaws.auth.BasicAWSCredentials;
|
||||
import com.amazonaws.regions.Regions;
|
||||
import com.amazonaws.services.sqs.AmazonSQSClientBuilder;
|
||||
import com.amazonaws.services.sqs.model.CreateQueueRequest;
|
||||
import com.amazonaws.services.sqs.model.DeleteMessageRequest;
|
||||
import com.amazonaws.services.sqs.model.GetQueueAttributesRequest;
|
||||
import com.amazonaws.services.sqs.model.GetQueueAttributesResult;
|
||||
import com.amazonaws.services.sqs.model.MessageAttributeValue;
|
||||
import com.amazonaws.services.sqs.model.ReceiveMessageRequest;
|
||||
import com.amazonaws.services.sqs.model.SendMessageBatchRequest;
|
||||
import com.amazonaws.services.sqs.model.SendMessageRequest;
|
||||
import com.amazonaws.services.sqs.model.SetQueueAttributesRequest;
|
||||
import com.amazonaws.services.sqs.model.SendMessageBatchRequestEntry;
|
||||
import com.amazonaws.services.sqs.model.Message;
|
||||
import com.amazonaws.services.sqs.AmazonSQS;
|
||||
|
||||
public class SQSApplication {
|
||||
|
||||
private static final AWSCredentials credentials;
|
||||
|
||||
static {
|
||||
// put your accesskey and secretkey here
|
||||
credentials = new BasicAWSCredentials(
|
||||
"<AWS accesskey>",
|
||||
"<AWS secretkey>"
|
||||
);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
// Set up the client
|
||||
AmazonSQS sqs = AmazonSQSClientBuilder.standard()
|
||||
.withCredentials(new AWSStaticCredentialsProvider(credentials))
|
||||
.withRegion(Regions.US_EAST_1)
|
||||
.build();
|
||||
|
||||
// Create a standard queue
|
||||
|
||||
CreateQueueRequest createStandardQueueRequest = new CreateQueueRequest("baeldung-queue");
|
||||
String standardQueueUrl = sqs.createQueue(createStandardQueueRequest)
|
||||
.getQueueUrl();
|
||||
|
||||
System.out.println(standardQueueUrl);
|
||||
|
||||
// Create a fifo queue
|
||||
|
||||
Map<String, String> queueAttributes = new HashMap<String, String>();
|
||||
queueAttributes.put("FifoQueue", "true");
|
||||
queueAttributes.put("ContentBasedDeduplication", "true");
|
||||
|
||||
CreateQueueRequest createFifoQueueRequest = new CreateQueueRequest("baeldung-queue.fifo").withAttributes(queueAttributes);
|
||||
String fifoQueueUrl = sqs.createQueue(createFifoQueueRequest)
|
||||
.getQueueUrl();
|
||||
|
||||
System.out.println(fifoQueueUrl);
|
||||
|
||||
// Set up a dead letter queue
|
||||
|
||||
String deadLetterQueueUrl = sqs.createQueue("baeldung-dead-letter-queue")
|
||||
.getQueueUrl();
|
||||
|
||||
GetQueueAttributesResult deadLetterQueueAttributes = sqs.getQueueAttributes(new GetQueueAttributesRequest(deadLetterQueueUrl).withAttributeNames("QueueArn"));
|
||||
|
||||
String deadLetterQueueARN = deadLetterQueueAttributes.getAttributes()
|
||||
.get("QueueArn");
|
||||
|
||||
SetQueueAttributesRequest queueAttributesRequest = new SetQueueAttributesRequest().withQueueUrl(standardQueueUrl)
|
||||
.addAttributesEntry("RedrivePolicy", "{\"maxReceiveCount\":\"2\", " + "\"deadLetterTargetArn\":\"" + deadLetterQueueARN + "\"}");
|
||||
|
||||
sqs.setQueueAttributes(queueAttributesRequest);
|
||||
|
||||
// Send a message to a standard queue
|
||||
|
||||
Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
|
||||
|
||||
messageAttributes.put("AttributeOne", new MessageAttributeValue().withStringValue("This is an attribute")
|
||||
.withDataType("String"));
|
||||
|
||||
SendMessageRequest sendMessageStandardQueue = new SendMessageRequest().withQueueUrl(standardQueueUrl)
|
||||
.withMessageBody("A simple message.")
|
||||
.withDelaySeconds(30) // Message will arrive in the queue after 30 seconds. We can use this only in standard queues
|
||||
.withMessageAttributes(messageAttributes);
|
||||
|
||||
sqs.sendMessage(sendMessageStandardQueue);
|
||||
|
||||
// Send a message to a fifo queue
|
||||
|
||||
SendMessageRequest sendMessageFifoQueue = new SendMessageRequest().withQueueUrl(fifoQueueUrl)
|
||||
.withMessageBody("FIFO Queue")
|
||||
.withMessageGroupId("baeldung-group-1")
|
||||
.withMessageAttributes(messageAttributes);
|
||||
|
||||
sqs.sendMessage(sendMessageFifoQueue);
|
||||
|
||||
// Send multiple messages
|
||||
|
||||
List<SendMessageBatchRequestEntry> messageEntries = new ArrayList<>();
|
||||
messageEntries.add(new SendMessageBatchRequestEntry().withId("id-1")
|
||||
.withMessageBody("batch-1")
|
||||
.withMessageGroupId("baeldung-group-1"));
|
||||
messageEntries.add(new SendMessageBatchRequestEntry().withId("id-2")
|
||||
.withMessageBody("batch-2")
|
||||
.withMessageGroupId("baeldung-group-1"));
|
||||
|
||||
SendMessageBatchRequest sendMessageBatchRequest = new SendMessageBatchRequest(fifoQueueUrl, messageEntries);
|
||||
sqs.sendMessageBatch(sendMessageBatchRequest);
|
||||
|
||||
// Read a message from a queue
|
||||
|
||||
ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(fifoQueueUrl).withWaitTimeSeconds(10) // Long polling;
|
||||
.withMaxNumberOfMessages(1); // Max is 10
|
||||
|
||||
List<Message> sqsMessages = sqs.receiveMessage(receiveMessageRequest)
|
||||
.getMessages();
|
||||
|
||||
sqsMessages.get(0)
|
||||
.getAttributes();
|
||||
sqsMessages.get(0)
|
||||
.getBody();
|
||||
|
||||
// Delete a message from a queue
|
||||
|
||||
sqs.deleteMessage(new DeleteMessageRequest().withQueueUrl(fifoQueueUrl)
|
||||
.withReceiptHandle(sqsMessages.get(0)
|
||||
.getReceiptHandle()));
|
||||
|
||||
// Monitoring
|
||||
GetQueueAttributesRequest getQueueAttributesRequest = new GetQueueAttributesRequest(standardQueueUrl).withAttributeNames("All");
|
||||
GetQueueAttributesResult getQueueAttributesResult = sqs.getQueueAttributes(getQueueAttributesRequest);
|
||||
System.out.println(String.format("The number of messages on the queue: %s", getQueueAttributesResult.getAttributes()
|
||||
.get("ApproximateNumberOfMessages")));
|
||||
System.out.println(String.format("The number of messages in flight: %s", getQueueAttributesResult.getAttributes()
|
||||
.get("ApproximateNumberOfMessagesNotVisible")));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user