0
Building Spring applications on
Cloud Foundry - a Marriage Made in
Heaven
by Andy Piper and Josh Long
© 2013 SpringOne 2GX...
About Andy Piper
Developer Advocate @ Cloud Foundry
social web enthusiast
maker, educator, LEGO fan
OSS contributor
Eclips...
About Josh Long
Developer Advocate
interested in big data, the open
web, cloud and all things Spring

3

@starbuxman
josh....
What is a “developer advocate”?
Today’s topics!
§ What is Cloud Foundry?
§ What’s new since #s2gx 2012?
§ run.pivotal.io
§ Java buildpack and Spring
§...
6
Spring
Deploy to Cloud
or on premise

Big,
Fast,
Flexible
Data
GemFire

Web,
Integration,
Batch
POP QUIZ:

Cloud Foundry? Platform CF?
What is Cloud Foundry, and what’s new?

9
Cloud Foundry is Part of the Pivotal Suite
Data-Driven
Application
Development

Pivotal Data
Science Labs

Pivotal Cloud
F...
The industry’s open
Platform as a Service

Deploy and scale applications in
seconds on your choice of clouds
STANDARDIZED ...
Platform as a Service (aka PaaS)
Empower developers to build great apps, not plumbing infrastructure
Ÿ An abstraction lay...
Simplify Application Deployment, from: this…

* An actual application provisioning/update flow in a large enterprise. Imag...
To: Pushing apps to the cloud with a few easy verbs
OPERATOR

DEVELOPER

cf-­‐iaas.yml

target	
  <my	
  cloud>

provision...
A Foundation Based on Choice
What:

Runtime/Frameworks

Services

How:

Buildpacks

Service Brokers

Which:

… and Custom ...
From VM Centric to Application Centric
App

App

App

App

Dev Framework

Dev Framework

Dev Framework

Configurations

Co...
Multi-Clouds, No App Changes!
Ÿ Your Datacenter / Private Clouds
– Cloud Foundry Lighthouse Program
– Packaged product co...
A LOT CAN HAPPEN IN 12 MONTHS!

What’s new since SpringOne 2012?
New features
•
•
•
•
•

19

a whole new architecture (“v2” or “ng”)
organizations and spaces (team features)
new router, w...
Cloud Foundry – The Inner Shell
Dynamic	
  Router
Cloud	
  Controller
UAA/Login	
  Servers
Service	
  Broker	
  Node(s)

H...
CLOUD FOUNDRY

Demo
Java buildpack
• Fully rebuilt for Cloud Foundry by the Spring team
• Choice of containers e.g. web, Grails, Play, Groovy,...
Choice!
• IBM donated WebSphere Liberty Buildpack
• http://blog.cloudfoundry.com/2013/09/09/ibm-websphereliberty-buildpack...
CLOUD FOUNDRY

Demo
Spring Tool Suite
• Updated to support Cloud Foundry v2

25
CLOUD FOUNDRY

Demo
Service Creation and Binding
VCAP_APPLICATION={"instance_id":"e4e2d8e0f66552df3bc8eba5ac2de23b","instan
ce_index":0,"host"...
The Environment
• Asking Questions
– You can introspect the environment variables
(System.getenv(“..”)), or...
– import th...
The Environment
• Ask Questions of the Cloud
– import the CloudFoundry runtime API
CloudEnvironment cloudEnvironment = new...
Auto-Reconfiguration: Getting Started
• Deploy Spring apps to the cloud without changing a single
line of code
• Cloud Fou...
Auto-Reconfiguration: Relational DB
•

Detects beans of type javax.sql.DataSource

•

Connects to MySQL or PostgreSQL serv...
Auto-Reconfiguration: How It Works
• Cloud Foundry installs a BeanFactoryPostProcessor in
your application context during ...
Introducing... the cloud Namespace
•
•
•
•

<cloud:> namespace for use in Spring app contexts
Provides application-level c...
<cloud:service-scan>
• Scans all services bound to the application and creates a
bean of an appropriate type for each
– Sa...
<cloud:service-scan> Autowired
•
•

Created beans can be autowired as dependencies
Use @Qualifier with service name if mult...
<cloud:data-source>
• Configures a DataSource bean
– Commons DBCP or Tomcat DataSource

• Basic attributes:
– id: defaults...
<cloud:data-source> Example
<cloud:data-source id="dataSource" service-name="mySQLSvc">
<cloud:pool pool-size="1-5"/>
<clo...
<cloud:properties>
•

Exposes basic information about services that can be consumed with Spring’s property
placeholder sup...
Spring Environment Abstraction
• Bean definitions for a specific environment (Profiles)
– e.g. development, testing, produ...
Isolating Cloud Foundry Configuration
• Switch between local, testing and Cloud Foundry
deployments with Profiles

40
Isolating Cloud Foundry Configuration
<bean class="org.sf.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name=...
Cloud Properties
• Cloud Foundry uses Environment abstraction to
automatically expose properties to Spring apps
– Basic in...
Cloud Properties Example
• Use service properties to create your own connection
factories (e.g., with c3p0)
import com.mch...
Profile Support: How It Works
• Cloud Foundry installs a custom
ApplicationContextInitializer in your app during staging
–...
Java Configuration
• Alternative to <cloud:*> namespace
– Spring Java Configuration
– Non-Spring apps

• Programmatic crea...
Using ServiceCreator
//Provides access to CF service and application env info
CloudEnvironment environment = new CloudEnvi...
Using ServiceInfo
//Provides access to CF service and application env info
CloudEnvironment environment = new CloudEnviron...
CLOUD FOUNDRY

Demo
Using ServiceInfo
//Provides access to CF service and application env info
CloudEnvironment environment = new CloudEnviron...
Any Questions?

Twitter: @andypiper @starbuxman
@springcentral @cloudfoundry
Find session replays on YouTube:
spring.io/vi...
Upcoming SlideShare
Loading in...5
×

Building Spring Applications on Cloud Foundry

2,743

Published on

Speakers: Josh Long and Andy Piper
Let's face it, the cloud is here to stay. The cloud's potential can seem sometimes overwhelming, but it doesn't have to if you use Spring. Spring - and the various Spring projects - already embrace the architecture characteristics that make for great, cloud-centric applications in any environment. While Spring works well on any cloud platform, it enjoys a special place in the sun on Cloud Foundry, the open source PaaS from Pivotal.
In this talk, join Andy Piper as he introduces how to build Spring applications that work well in the cloud and on Cloud Foundry in particular. We'll cover how to consume services with Spring on Cloud Foundry, how to scale out using RabbitMQ and Spring Integration, how to use standalone processes and RabbitMQ for better batch processing, and discuss strategies for exposing and consuming services in a RESTful service-based cloud architecture.

Published in: Technology
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,743
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
85
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide

Transcript of "Building Spring Applications on Cloud Foundry"

  1. 1. Building Spring applications on Cloud Foundry - a Marriage Made in Heaven by Andy Piper and Josh Long © 2013 SpringOne 2GX. All rights reserved. Do not distribute without permission.
  2. 2. About Andy Piper Developer Advocate @ Cloud Foundry social web enthusiast maker, educator, LEGO fan OSS contributor Eclipse Project Lead (Paho / MQTT) excited by “what’s next”, Internet of Things, etc. @andypiper apiper@gopivotal.com 2
  3. 3. About Josh Long Developer Advocate interested in big data, the open web, cloud and all things Spring 3 @starbuxman josh.long@springsource.com
  4. 4. What is a “developer advocate”?
  5. 5. Today’s topics! § What is Cloud Foundry? § What’s new since #s2gx 2012? § run.pivotal.io § Java buildpack and Spring § demos!
  6. 6. 6
  7. 7. Spring Deploy to Cloud or on premise Big, Fast, Flexible Data GemFire Web, Integration, Batch
  8. 8. POP QUIZ: Cloud Foundry? Platform CF?
  9. 9. What is Cloud Foundry, and what’s new? 9
  10. 10. Cloud Foundry is Part of the Pivotal Suite Data-Driven Application Development Pivotal Data Science Labs Pivotal Cloud Fabric Pivotal Data Fabric GemFire Virtualization ...++ Cloud Storage
  11. 11. The industry’s open Platform as a Service Deploy and scale applications in seconds on your choice of clouds STANDARDIZED FOR SPEED
  12. 12. Platform as a Service (aka PaaS) Empower developers to build great apps, not plumbing infrastructure Ÿ An abstraction layer on top of IaaS SaaS Ÿ Application is the unit of deployment – not VMs, AppServers, etc.. PaaS Ÿ Separate the concerns of AppDev & Operations – Databases, Messaging, Load-balancing etc.. “aaS” Ÿ Eliminate bottleneck of provisioning and deployment Ÿ Make full use of investments in the “Cloud” IaaS
  13. 13. Simplify Application Deployment, from: this… * An actual application provisioning/update flow in a large enterprise. Image is blurred for privacy reasons
  14. 14. To: Pushing apps to the cloud with a few easy verbs OPERATOR DEVELOPER cf-­‐iaas.yml target  <my  cloud> provision  <my  cloud> push  <my  app> add_capacity  <my  cloud> create  <my  services> bind  <my  services> scale  <my  app>  +100 Cloud  Deployment:    2-­‐4  hours App  Deployment:    30-­‐90  seconds
  15. 15. A Foundation Based on Choice What: Runtime/Frameworks Services How: Buildpacks Service Brokers Which: … and Custom Runtimes 15 … and Custom Services
  16. 16. From VM Centric to Application Centric App App App App Dev Framework Dev Framework Dev Framework Configurations Configurations Manifests, Automations JVM JVM App Server App Server VM Infrastructure One 16 VM Infrastructure Two Container 1 Container 2 JVM JVM App Server App Server Infrastructure One Infrastructure Two
  17. 17. Multi-Clouds, No App Changes! Ÿ Your Datacenter / Private Clouds – Cloud Foundry Lighthouse Program – Packaged product coming soon Ÿ Hosted / Public Clouds – run.pivotal.io – Other Cloud Foundry public PaaS via partners (e.g. anynines) Ÿ Developer Laptop – micro clouds as free developer tool Public Clouds Private Clouds Micro Clouds
  18. 18. A LOT CAN HAPPEN IN 12 MONTHS! What’s new since SpringOne 2012?
  19. 19. New features • • • • • 19 a whole new architecture (“v2” or “ng”) organizations and spaces (team features) new router, with added WebSockets new DEAs, with built-in stager and buildpacks new Services model, with Marketplace feature
  20. 20. Cloud Foundry – The Inner Shell Dynamic  Router Cloud  Controller UAA/Login  Servers Service  Broker  Node(s) Health  Manager DEA  Pool(s) Apps User  Provided Service  Instances CF  RunIme Buildpacks The Runtime is the inner shell. Components are dynamically discoverable and loosely coupled, exposing health through HTTP endpoints so agents can collect state information (app state & system state) and act on it. Logging Messaging  (NATS) Cloud  Foundry  BOSH CF  BOSH BOSH is the outer shell
  21. 21. CLOUD FOUNDRY Demo
  22. 22. Java buildpack • Fully rebuilt for Cloud Foundry by the Spring team • Choice of containers e.g. web, Grails, Play, Groovy, Java main(), Spring Boot, etc • Configurable • Pluggable / extensible (Dropwizard, Jonas, etc etc.) • http://blog.cloudfoundry.com/2013/09/06/introducing-thecloud-foundry-java-buildpack/ • https://github.com/cloudfoundry/java-buildpack 22
  23. 23. Choice! • IBM donated WebSphere Liberty Buildpack • http://blog.cloudfoundry.com/2013/09/09/ibm-websphereliberty-buildpack-contributed-to-cloud-foundry/ 23
  24. 24. CLOUD FOUNDRY Demo
  25. 25. Spring Tool Suite • Updated to support Cloud Foundry v2 25
  26. 26. CLOUD FOUNDRY Demo
  27. 27. Service Creation and Binding VCAP_APPLICATION={"instance_id":"e4e2d8e0f66552df3bc8eba5ac2de23b","instan ce_index":0,"host":"0.0.0.0","port":61797,"started_at":"2013-09-09 00:43:36 +0000","started_at_timestamp":1378687416,"start":"2013-09-09 00:43:36 +0000","state_timestamp":1378687416,"limits":{"mem":512,"disk":1024,"fds": 16384},"application_version":"556843e0-63b2-4a6fbf1c-0f1fbc2eec95","application_name":"music-demo-ap","application_uris":["musicdemo-ap.cfapps.io"],"version":"556843e0-63b2-4a6fbf1c-0f1fbc2eec95","name":"music-demo-ap","uris":["music-demoap.cfapps.io"],"users":null} VCAP_SERVICES={"elephantsql-n/a":[{"name":"elephantsqlc299a","label":"elephantsql-n/a","tags": ["postgres","postgresql","relational"],"plan":"turtle","credentials":{"uri":"postgres:// wurble:N_zNcLVWdx4Um7DEsESAqQFGNrKi5pJc@babar.elephantsql.com:5432/ wurble"}}],"newrelic-n/a":[{"name":"newrelic-1764c","label":"newrelic-n/a","tags": [],"plan":"standard","credentials": {"licenseKey":"6f044737f4786878ad3870d7e84c78de3e9a70fce"}}]} 27
  28. 28. The Environment • Asking Questions – You can introspect the environment variables (System.getenv(“..”)), or... – import the CloudFoundry runtime API from Java! • (much simpler) <dependency> <groupId>org.cloudfoundry</groupId> <artifactId>cloudfoundry-runtime</artifactId> <version>0.8.5</version> </dependency> 28
  29. 29. The Environment • Ask Questions of the Cloud – import the CloudFoundry runtime API CloudEnvironment cloudEnvironment = new CloudEnvironment(); if (cloudEnvironment.getCloudApiUri() != null) { model.put("host", cloudEnvironment.getInstanceInfo().getHost()); model.put("port", cloudEnvironment.getInstanceInfo().getPort()); } 29
  30. 30. Auto-Reconfiguration: Getting Started • Deploy Spring apps to the cloud without changing a single line of code • Cloud Foundry automatically re-configures bean definitions to bind to cloud services • Works with Spring and Grails 30
  31. 31. Auto-Reconfiguration: Relational DB • Detects beans of type javax.sql.DataSource • Connects to MySQL or PostgreSQL services – Specifies driver, url, username, password, validation query • Creates Commons DBCP or Tomcat DataSource • Replaces existing DataSource import org.apache.commons.dbcp.BasicDataSource; ... @Bean(destroyMethod = "close") public BasicDataSource dataSource(){ BasicDataSource bds = new BasicDataSource(); bds.setUrl( "jdbc:h2:mem"); bds.setPassword(""); bds.setUsername("sa"); bds.setDriverClass( Driver.class); return bds; } 31
  32. 32. Auto-Reconfiguration: How It Works • Cloud Foundry installs a BeanFactoryPostProcessor in your application context during staging – Adds jar to your application – Modifies web.xml to load BFPP • Adds context file to contextConfigLocation – web-app context-param – Spring MVC DispatcherServlet init-param • Adds PostgreSQL and MySQL driver jars as needed for DataSource reconfiguration 32
  33. 33. Introducing... the cloud Namespace • • • • <cloud:> namespace for use in Spring app contexts Provides application-level control of bean service bindings Recommended for development of new cloud apps Use when: – You have multiple services of the same type – You have multiple connecting beans of the same type • e.g. DataSource, MongoDBFactory – You have custom bean configuration • e.g. DataSource pool size, connection properties 33
  34. 34. <cloud:service-scan> • Scans all services bound to the application and creates a bean of an appropriate type for each – Same bean types as auto-reconfiguration • Useful during early development phases <beans ... xmlns:cloud="http://schema.cloudfoundry.org/spring" xsi:schemaLocation="http://schema.cloudfoundry.org/spring http://schema.cloudfoundry.org/spring/cloudfoundry-spring-0.8.xsd ..."> <cloud:service-scan/> </beans> 34
  35. 35. <cloud:service-scan> Autowired • • Created beans can be autowired as dependencies Use @Qualifier with service name if multiple services of same type bound to app @Autowired(required=false) private ConnectionFactory rabbitConnectionFactory; @Autowired private RedisConnectionFactory redisConnectionFactory; @Autowired @Qualifier("test_mysql_database") private DataSource mysqlDataSource; @Autowired(required=false) @Qualifier("test_postgres_database") private DataSource postgresDataSource; 35
  36. 36. <cloud:data-source> • Configures a DataSource bean – Commons DBCP or Tomcat DataSource • Basic attributes: – id: defaults to service name – service-name: only needed if you have multiple relational database services bound to the app <cloud:data-source id="dataSource"/> <bean class="org.sf.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory"> <property name="dataSource" ref="dataSource"/> </bean> 36
  37. 37. <cloud:data-source> Example <cloud:data-source id="dataSource" service-name="mySQLSvc"> <cloud:pool pool-size="1-5"/> <cloud:connection properties="charset=utf-8"/> </cloud:data-source> ... @Autowired private DataSource dataSource ; 37
  38. 38. <cloud:properties> • Exposes basic information about services that can be consumed with Spring’s property placeholder support • Basic attributes: – • id: the name of the properties bean Properties automatically available when deploying Spring 3.1 applications <cloud:properties id="cloudProperties" /> <context:property-placeholder properties-ref="cloudProperties"/> @Autowired private Environment environment; 38 @Bean public ComboPooledDataSource dataSource() throws Exception { String user = this.environment.getProperty ("cloud.services.mysql.connection.username"); ComboPooledDataSource cpds = new ComboPooledDataSource(); cpds.setUser(user); return cpds; }
  39. 39. Spring Environment Abstraction • Bean definitions for a specific environment (Profiles) – e.g. development, testing, production – Possibly different deployment environments – Activate profiles by name • spring.profiles.active system property • Other means outside deployment unit • “default” profile activates if no other profiles specified • Custom resolution of placeholders – Dependent on the actual environment – Ordered property sources 39
  40. 40. Isolating Cloud Foundry Configuration • Switch between local, testing and Cloud Foundry deployments with Profiles 40
  41. 41. Isolating Cloud Foundry Configuration <bean class="org.sf.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource"/> </bean> <beans profile="cloud"> <cloud:data-source id="dataSource" /> </beans> <beans profile="default"> <bean class="org.a.commons.dbcp.BasicDataSource" id="dataSource"> <property name="url" value="jdbc:mysql://localhost/my_db" /> </bean> </beans> 41
  42. 42. Cloud Properties • Cloud Foundry uses Environment abstraction to automatically expose properties to Spring apps – Basic information about the application, such as its name and the cloud provider – Detailed connection information for bound services • cloud.services.{service-name}.connection.{property} • aliases for service name created based on the service type – e.g. “cloud.services.mysql.connection.{property}” – only if there is a single service for that type bound 42
  43. 43. Cloud Properties Example • Use service properties to create your own connection factories (e.g., with c3p0) import com.mchange.v2.c3p0.* ; @Autowired private Environment e; @Bean public ComboPooledDataSource cpds (){ ComboPooledDataSource cpds = new ComboPooledDataSource (); String host=e.getProperty("cloud.services.mysql.connection.host"), port=e.getProperty("cloud.services.mysql.connection.port"), name=e.getProperty("cloud.services.mysql.connection.name"), pw=e.getProperty("cloud.services.mysql.connection.password"); cpds.set...( host ... ); return cpds; } 43
  44. 44. Profile Support: How It Works • Cloud Foundry installs a custom ApplicationContextInitializer in your app during staging – Modifies web.xml • Adds to contextInitializerClasses context-param • Adds a PropertySource to the Environment 44
  45. 45. Java Configuration • Alternative to <cloud:*> namespace – Spring Java Configuration – Non-Spring apps • Programmatic creation of service connection factories – Using ServiceCreator and ServiceInfo classes • CloudEnvironment class provides access to all cloud properties and service info without requiring JSON parsing • Included in cloudfoundry-runtime lib 45
  46. 46. Using ServiceCreator //Provides access to CF service and application env info CloudEnvironment environment = new CloudEnvironment(); //Retrieve env info for bound service named "mysqlService" RdbmsServiceInfo mysqlSvc = environment.getServiceInfo("mysqlService", RdbmsServiceInfo.class); //create a DataSource bound to the service RdbmsServiceCreator dataSourceCreator = new RdbmsServiceCreator(); DataSource dataSource = dataSourceCreator.createService(mysqlSvc); 46
  47. 47. Using ServiceInfo //Provides access to CF service and application env info CloudEnvironment environment = new CloudEnvironment(); //Retrieve env info for bound service named "mongoService" MongoServiceInfo mongoSvc = environment.getServiceInfo("mongoService", MongoServiceInfo.class); //create a Mongo DB bound to the service Mongo mongoDB = new Mongo(mongoSvc.getHost(), mongoSvc.getPort()); 47
  48. 48. CLOUD FOUNDRY Demo
  49. 49. Using ServiceInfo //Provides access to CF service and application env info CloudEnvironment environment = new CloudEnvironment(); //Retrieve env info for bound service named "mongoService" MongoServiceInfo mongoSvc = environment.getServiceInfo("mongoService", MongoServiceInfo.class); //create a Mongo DB bound to the service Mongo mongoDB = new Mongo(mongoSvc.getHost(), mongoSvc.getPort()); 49
  50. 50. Any Questions? Twitter: @andypiper @starbuxman @springcentral @cloudfoundry Find session replays on YouTube: spring.io/video
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×