Tiven Wang
chevron_rightSpring Cloud chevron_rightCloud Foundry

Try Cloud Foundry 8 - Spring Cloud Connector

Wang Tiven July 25, 2017
425 favorite favorites
bookmark bookmark
share share

Autumn Grizzly Denali National Park, Alaska

spring-boot-starter-cloud-connectors is a starter for using Spring Cloud Connectors which simplifies connecting to services in cloud platforms like Cloud Foundry and Heroku.

下載本篇完整代碼 Github

Setup

添加 Spring Boot 的 Cloud connectors starter

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-cloud-connectors</artifactId>
</dependency>

MongoDB

為了測試 Cloud connectors 的數據庫連接效果,這裡我們使用 mongodb 數據庫服務。

添加 Spring Boot starter 的 spring data mongodb 組件

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

Model

新建一個 MongoDB 文檔模型 Hero:

@Document(collection = "hero")
public class Hero {

  @Id
  @JsonSerialize(using = ToStringSerializer.class)
  private BigInteger id;

  private String name;

  ...
}

Repository

為 Hero 模型創建一個 Repository, 只有簡單的CRUD操作的 Repository:

public interface HeroRepository  extends CrudRepository<Hero, BigInteger> {
}

Controller

在 Controller 裡使用 HeroRepository 來操作數據庫進行增刪改查:

@RestController
@RequestMapping("/hero")
public class HeroController {

  @Autowired(required = false) HeroRepository heroRepository;

  @RequestMapping("")
  Iterable<Hero> getAll() {
    return heroRepository.findAll();
  }

  @RequestMapping(path="", method=RequestMethod.POST)
  Hero create(@RequestBody Hero hero) {
    return heroRepository.save(hero);
  }

  @RequestMapping("/{id}")
  Hero get(@PathVariable BigInteger id) {
    return heroRepository.findOne(id);
  }

  @RequestMapping(path="/{id}", method=RequestMethod.DELETE)
  void delete(@PathVariable BigInteger id) {
    heroRepository.delete(id);
  }
}

Cloud Configuration

為了告訴 Spring 如果去創建 Cloud 的環境配置,需要創建類 CloudConfiguration:

@Configuration
@ServiceScan
@Profile("cloud")
public class CloudConfiguration extends AbstractCloudConfig {
  @Bean
  public ApplicationInstanceInfo applicationInfo() {
    return cloud().getApplicationInstanceInfo();
  }
}
  • @ServiceScan 註解類似Spring中的@ComponentScan, 它會掃描綁定在此app上的服務,並為每個服務創建一個bean
  • @Profile("cloud") 說明當程序指定激活cloud配置时才加载这里的配置, 如在manifest.yml中指定
    # ...
    env:
    SPRING_PROFILES_ACTIVE: cloud
    

Test

可以在本機啟動一個MongoDB服務,因為本機運行不起用 profile cloud 時默認使用localhost的 MongoDB 服務。

例如使用docker在本機創建一個MongoDB服務

docker run --rm --name my-mongo -d -p 27017:27017 mongo

然後啟動應用 mvn spring:run

訪問鏈接 http://localhost:8080/hero 則可以創建查詢 Hero。

Deploy

像之前講的方式一樣 push 到 CloudFoundry 上去

mvn clean package

cf push

但還需要在 CloudFoundry 上創建一個 MongoDB 服務:

cf create-service mlab sandbox try-cf-mongodb

並綁定到此應用:

cf bind-service try-cf-spring-boot try-cf-mongodb

重啟應用:

cf restart

訪問鏈接 https://try-cf-spring-boot.cfapps.io/hero 可以增刪查Hero啦。

Manifest

或者使用 manifest 配置文件部署

---
applications:
- name: try-cf-spring-boot
  buildpack: java_buildpack
  instances: 1
  memory: 1G
  host: try-cf-spring-boot
  env:
    APP_LOGGING_LEVEL: DEBUG
    SPRING_PROFILES_ACTIVE: cloud
  path: target/try-cf-spring-boot-0.0.1-SNAPSHOT.jar
  services:
    - try-cf-mongodb

References

Similar Posts

  • Try Cloud Foundry 13 - Logs Loggregator is the next generation system for aggregating and streaming logs and metrics from all of the user apps and system components in an Elastic Runtime deployment. Loggregator uses Google's protocol buffers along with gRPC to deliver logs.
  • Try Cloud Foundry 12 - Config Server Config Server for Pivotal Cloud Foundry (PCF) is an externalized application configuration service, which gives you a central place to manage an application’s external properties across all environments.
  • Try Cloud Foundry 11 - Autoscaler Autoscaler
  • Microservices - Load Balancing 在微服务架构中每个服务都可能有多个运行实例, 那么服务消费者在调用服务时怎么定位应该把请求发送给哪个实例呐? 这就是负载均衡 Load Balancing 要做的事情。Load Balancing 可以在服务端也可以是在消费端。
  • Microservices - Service Discovery Clients of a service use either Client-side discovery or Server-side discovery to determine the location of a service instance to which to send requests. Why use Service Discovery?
  • Try CloudFoundry Try CloudFoundry

Comments

comments powered by Disqus
Back to Top