Cloud Foundry samples学习笔记 3:services
在前一个样例程序hello-spring-mysql中,应用程序在开发时使用的是本地mysql服务,而在部署时通过自动重配置与Cloud Foundry提供的mysql云服务绑定。现在我们通过另一个简单的“services”样例程序来看一下如何在应用开发时直接使用Cloud Foundry的云服务,从而脱离与本地服务的依赖。
services样例程序所做的事情是,绑定了Cloud Foundry内部的数据源,并使用了mongodb和redis两种云服务。当接收到用户访问请求时,应用程序返回数据源的地址以及所有使用到的云服务的基本信息。
程序repository地址:https://github.com/SpringSource/cloudfoundry-samples/tree/master/services
程序源码位于 ”services/hello-services-namespace/src/main" 下,同样包含三个子目录:java,resources,webapp,目录结构与之前看过的样例程序基本相同。这里,我们重点关注三个文件:
pom.xml
webapp/WEB-INF/spring/root-context.xml
java/org/cloudfoundry/services/HomeController.java
pom.xml 文件
程序使用Maven构建,需要向pom.xml中添加 org.cloudfoundry:cloudfoundry-runtime 依赖项
print?<dependency>
<groupId>org.cloudfoundry</groupId>
<artifactId>cloudfoundry-runtime</artifactId>
<version>${org.cloudfoundry-version}</version>
</dependency>
程序中使用了mongodb、rabbitmq等,因此还需添加对应的spring-rabbit、spring-data-mongodb等依赖库。(具体见源文件)
root-context.xml 文件
print?<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:cloud="http://www.springframework.org/schema/cloud"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/cloud http://www.springframework.org/schema/cloud/spring-cloud.xsd">
<cloud:data-source/>
<cloud:mongo/>
<cloud:redis-connection-factory/>
</beans>
为了使用Cloud Foundry内部提供的云服务,就需要在应用程序中包含它的<cloud>命名空间。为此,需要在应用程序上下文中(即root-context.xml)声明该命名空间(第4行)并指明其schema的位置(第6行)。之后,就可以使用<cloud>标签来定义并配置各种服务了。作为简单的示例程序,这里仅仅对服务进行了绑定,并未做进一步配置和使用。有关更多<cloud>命名空间元素及其配置选项,请看这里
HomeController.java 文件
该文件中进行用户请求的处理操作。把<cloud>元素包含进应用程序上下文中之后,就可以在Java处理代码中添加@Autowired注释进行cloud服务bean的自动注入。
print?@Autowired(required=false) DataSource dataSource;
@Autowired(required=false) ConnectionFactory rabbitConnectionFactory;
@Autowired(required=false) RedisConnectionFactory redisConnectionFactory;
@Autowired(required=false) Mongo mongo;
@Autowired要求Spring 容器中匹配的候选 bean 数目必须有且仅有一个,否则将会抛出异常。于是,required=false的作用就是告诉Spring,即使找不到匹配的Bean也不报错,因为我们并未使用以上所有的bean。
总结
在pom.xml中添加Cloud Foundry运行时依赖库及所使用服务的spring支持库,在应用程序上下文中包含cloud命名空间并配置cloud元素bean,在Java代码中使用@Autowired进行自动注入。这样一来,就可以脱离本地服务,直接使用Cloud Foundry提供的内部云服务进行应用程序的开发了。