DynamoDB and TableNameOverride with prefix

前端 未结 3 1603
[愿得一人]
[愿得一人] 2021-02-20 01:54

I am testing DynamoDB tables and want to set up different table names for prod and dev environment using the prefix \"dev_\" for development.

I made this test to print t

3条回答
  •  借酒劲吻你
    2021-02-20 02:46

    Same as Paolo Almeidas solution, just with Spring-Boot annotations. Just wanted to share it and maybe save someone time:

    I have dynamodb tables for each namespace, e.g. myApp-dev-UserTable, myApp-prod-UserTable and I am using the EKS_NAMESPACE env variable, which in my case gets injected into the pods by kubernetes.

    import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
    import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
    import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
    import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig;
    
    @Configuration
    @EnableDynamoDBRepositories(basePackages = "de.dynamodb")
    public class DynamoDBConfig {
    
        @Value("${EKS_NAMESPACE}")
        String eksNamespace;
    
        @Bean
        public AmazonDynamoDB amazonDynamoDB() {
            return AmazonDynamoDBClientBuilder.standard()
                .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(
                        "dynamodb.eu-central-1.amazonaws.com", "eu-central-1"))
                .withCredentials(awsCredentials())
                .build();
        }
    
        @Bean
        public AWSCredentialsProvider awsCredentials() {
            return WebIdentityTokenCredentialsProvider.builder().build();
        }
    
        // Table Name override:
    
        @Bean
        public DynamoDBMapperConfig.TableNameOverride tableNameOverride() {
            return DynamoDBMapperConfig.TableNameOverride.withTableNamePrefix("myApp-" + eksNamespace + "-");
        }
    
        @Bean
        public DynamoDBMapperConfig dynamoDBMapperConfig() {
            return DynamoDBMapperConfig.builder().withTableNameOverride(tableNameOverride()).build();
        }
    
        @Bean
        // Marked as primary bean to override default bean.
        @Primary
        public DynamoDBMapper dynamoDBMapper() {
            return new DynamoDBMapper(amazonDynamoDB(), dynamoDBMapperConfig());
        }
    }
    

    With a table like this:

    @Data
    @DynamoDBTable(tableName = "UserTable")
    public class User {
    
            @DynamoDBHashKey
            private String userId;
    
            @DynamoDBAttribute
            private String foo;
    
            @DynamoDBAttribute
            private String bar;
    }
    

提交回复
热议问题