Spring Cloud AWS – EC2 – Spring Cloud AWS – EC2

最后修改: 2018年 1月 12日

中文/混合/英文(键盘快捷键:t)

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

前一篇文章中,我们重点介绍了S3;现在我们将重点介绍弹性计算云–通常被称为EC2。

1. EC2 Metadata Access

1.EC2元数据的访问

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:

这可以通过在任何配置类上添加@EnableContextInstanceData注解来启用。

@Configuration
@EnableContextInstanceData
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:

然后,我们可以注入这些值。

@Value("${ami-id}")
private String amiId;

@Value("${hostname}")
private String hostname;

@Value("${instance-type}")
private String instanceType;

@Value("${services/domain}")
private String serviceDomain;

1.1. Custom Tags

1.1.自定义标签

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:

此外,Spring还支持注入用户定义的标记。我们可以通过在context-instance-data中定义一个属性user-tags-map来启用这一功能,具体配置如下。

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

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

现在,让我们在Spring表达式语法的帮助下,注入用户定义的标签。

@Value("#{instanceData.myTagKey}")
private String myTagValue;

2. EC2 Client

2.EC2客户端

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:

此外,如果有为实例配置的用户标签,Spring将创建一个AmazonEC2客户端,我们可以使用@Autowired将其注入我们的代码中。

@Autowired
private AmazonEC2 amazonEc2;

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

请注意,这些功能只有在应用程序在EC2实例上运行时才能发挥作用。

3. Conclusion

3.结论

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.

系列的下一篇文章中,我们将探讨对RDS的支持。

As usual, the examples are available over on GitHub.

像往常一样,这些例子可以在GitHub上找到over

Next »

Spring Cloud AWS – RDS

« Previous

Spring Cloud AWS – S3