Spring Cloud AWS – EC2 – Spring Cloud AWS – EC2

最后修改: 2018年 1月 12日

In the previous article, we’re focusing on S3; now we’ll focus on the Elastic Compute Cloud – commonly known as EC2.


1. EC2 Metadata Access


The AWS EC2MetadataUtils class provides static methods to access instance metadata like AMI Id and instance type. With Spring Cloud AWS we can inject this metadata directly using the @Value annotation.

AWS的EC2MetadataUtils类提供了静态方法来访问实例元数据,如AMI Id和实例类型。通过Spring Cloud AWS,我们可以使用@Value注解直接注入这些元数据

This can be enabled by adding the @EnableContextInstanceData annotation over any of the configuration classes:


public class EC2EnableMetadata {

In a Spring Boot environment, instance metadata is enabled by default which means this configuration is not required.

在Spring Boot环境中,实例元数据是默认启用的,这意味着这种配置是不需要的

Then, we can inject the values:


private String amiId;

private String hostname;

private String instanceType;

private String serviceDomain;

1.1. Custom Tags


Additionally, Spring also supports injection of user-defined tags. We can enable this by defining an attribute user-tags-map in context-instance-data using the following XML configuration:


    <aws-context:context-instance-data user-tags-map="instanceData"/>

Now, let’s inject the user-defined tags with the help of Spring expression syntax:


private String myTagValue;

2. EC2 Client


Furthermore, if there are user tags configured for the instance, Spring will create an AmazonEC2 client which we can inject into our code using @Autowired:


private AmazonEC2 amazonEc2;

Please note that these features work only if the app is running on an EC2 instance.


3. Conclusion


This was a quick and to-the-point introduction to accessing EC2d data with Spring Cloud AWS.

这是对使用Spring Cloud AWS访问EC2d数据的一个快速和直接的介绍。

In the next article of the series, we’ll explore the RDS support.


As usual, the examples are available over on GitHub.


Next »

Spring Cloud AWS – RDS

« Previous

Spring Cloud AWS – S3