Showing posts with label AWS. Show all posts
Showing posts with label AWS. Show all posts

AWS Java SDK - automatically detect the region

When the app is deployed in multiple regions in AWS, its useful to detect the region automatically without specifying the region by using a property/environment variable ourself.


We can detect the region by using the AWS SDK:

    Regions.getCurrentRegion(); //returns Regions enum

Or by using:

    EC2MetadataUtils.getEC2InstanceRegion(); //returns region String

Or:

    System.getenv("AWS_REGION")

AWS DynamoDB - dynamic table prefix using DynamoDBMapper


We can use DynamoDBMapperConfig.TableNameOverride to configure the DynamoDBMapper and provide a custom/dynamic table name prefix using TableNameOverride.withTableNamePrefix(String).


Plain Java Example:

import com.amazonaws.services.dynamodbv2.*;
import com.amazonaws.services.dynamodbv2.datamodeling.*;

import java.util.UUID;

//code:

String prefix = "SOME_DYNAMIC_PREFIX"; //can be pulled from a dynamic logic eg: profile, env variable etc
var mapperConfig = new DynamoDBMapperConfig.Builder()
.withTableNameOverride(DynamoDBMapperConfig.TableNameOverride.withTableNamePrefix(prefix + "-"))
.build();

var dynamoDB = AmazonDynamoDBClientBuilder.standard().build();
var dbMapper = new DynamoDBMapper(dynamoDB, mapperConfig);


// use it
dbMapper.load(MyTable.class, UUID.randomUUID());

Spring DynamoDB dynamic table prefix example



import com.amazonaws.services.dynamodbv2.*;
import com.amazonaws.services.dynamodbv2.datamodeling.*;
import org.springframework.context.annotation.*;
import java.util.UUID;

@Configuration
class AwsConfig {
@Bean
AmazonDynamoDB dynamoDB() {
return AmazonDynamoDBClientBuilder.standard().build();
}

@Bean
DynamoDBMapperConfig dynamoDBMapperConfig() {
String prefix = "SOME_DYNAMIC_PREFIX"; //can be pulled from a dynamic logic eg: profile, env variable etc
return new DynamoDBMapperConfig.Builder()
.withTableNameOverride(DynamoDBMapperConfig.TableNameOverride.withTableNamePrefix(prefix + "-"))
.build();
}

@Bean
DynamoDBMapper dynamoDBMapper(AmazonDynamoDB dynamoDB, DynamoDBMapperConfig dynamoDBMapperConfig)
{
return new DynamoDBMapper(dynamoDB, dynamoDBMapperConfig);
}
}


import com.amazonaws.services.dynamodbv2.datamodeling.*;
import java.util.UUID;
@DynamoDBTable(tableName = "person")
public class MyTable {
@DynamoDBHashKey
@DynamoDBAutoGeneratedKey
UUID id;

String name;
//getter setter/other fields