Spring Cloud - Bootstrapping

1. Общ преглед

Spring Cloud е рамка за изграждане на стабилни облачни приложения. Рамката улеснява разработването на приложения, като предоставя решения на много от често срещаните проблеми, с които се сблъскват при преместване в разпределена среда.

Приложенията, които се изпълняват с архитектура на микроуслуги, имат за цел да опростят разработването, внедряването и поддръжката. Декомпозираният характер на приложението позволява на разработчиците да се фокусират върху един проблем в даден момент. Подобрения могат да бъдат въведени, без да се засягат други части на системата.

От друга страна, възникват различни предизвикателства, когато възприемем микросервизния подход:

  • Екстернализиране на конфигурацията, така че да е гъвкава и да не изисква възстановяване на услугата при промяна
  • Откриване на услугата
  • Скриване на сложността на услугите, разположени на различни хостове

В тази статия ще изградим пет микроуслуги: сървър за конфигуриране, сървър за откриване, сървър за шлюз, услуга за книги и накрая услуга за оценка. Тези пет микроуслуги формират солидно основно приложение, за да започнат разработването на облак и да отговорят на гореспоменатите предизвикателства.

2. Конфигуриране на сървър

При разработването на облачно приложение един проблем е поддържането и разпространението на конфигурацията към нашите услуги. Наистина не искаме да отделяме време за конфигуриране на всяка среда, преди да мащабираме хоризонтално нашата услуга или да рискуваме пробиви в сигурността, като изпечем нашата конфигурация в нашето приложение.

За да разрешим това, ще консолидираме цялата си конфигурация в едно Git хранилище и ще свържем това с едно приложение, което управлява конфигурация за всички наши приложения. Ще създадем много проста реализация.

За да научите повече подробности и да видите по-сложен пример, разгледайте статията ни за Spring Cloud Configuration.

2.1. Настройвам

Придвижете се до //start.spring.io и изберете Maven и Spring Boot 2.2.x.

Задайте артефакта на „config . В раздела за зависимости потърсете „config server“ и добавете този модул. След това натиснете бутона за генериране и ще можем да изтеглим zip файл с предварително конфигуриран проект вътре и готов за работа.

Като алтернатива можем да генерираме проект за Spring Boot и да добавим ръчно някои зависимости към POM файла.

Тези зависимости ще бъдат споделени между всички проекти:

 org.springframework.boot spring-boot-starter-parent 2.2.6.RELEASE     org.springframework.boot spring-boot-starter-test test      org.springframework.cloud spring-cloud-dependencies Hoxton.SR4 pom import       org.springframework.boot spring-boot-maven-plugin   

Нека добавим зависимост за конфигурационния сървър:

 org.springframework.cloud spring-cloud-config-server 

За справка можем да намерим най-новата версия на Maven Central ( пролетни облачни зависимости, тест, конфигурационен сървър ).

2.2. Spring Config

За да активираме конфигурационния сървър, трябва да добавим някои пояснения към основния клас на приложението:

@SpringBootApplication @EnableConfigServer public class ConfigApplication {...}

@EnableConfigServer ще превърне нашето приложение в конфигурационен сървър.

2.3. Имоти

Нека добавим application.properties в src / main / resources :

server.port=8081 spring.application.name=config spring.cloud.config.server.git.uri=file://${user.home}/application-config

Най-важната настройка за конфигурационния сървър е параметърът git.uri . Понастоящем това е зададено на относителна файлова пътека, която обикновено се разрешава на c: \ Users \ {потребителско име} \ в Windows или / Users / {потребителско име} / на * nix. Това свойство сочи към Git хранилище, където се съхраняват файловете на свойствата за всички останали приложения. При необходимост може да бъде зададен на абсолютен път до файла.

Съвет : На машина с Windows предговорете стойността с “file: ///”, на * nix след това използвайте “file: //”.

2.4. Хранилище на Git

Отидете до папката, определена от spring.cloud.config.server.git.uri и добавете папката application-config . CD в ​​тази папка и напишете git init . Това ще инициализира хранилище на Git, където можем да съхраняваме файлове и да проследяваме техните промени.

2.5. Бягай

Нека да стартираме конфигурационния сървър и да се уверим, че работи. От командния ред напишете mvn spring-boot: run . Това ще стартира сървъра.

Трябва да видим този изход, показващ, че сървърът работи:

Tomcat started on port(s): 8081 (http)

2.6. Конфигурация за стартиране

В следващите ни сървъри ще искаме свойствата на техните приложения да се управляват от този конфигурационен сървър. За да направим това, всъщност ще трябва да направим малко пилешко и яйце: Конфигуриране на свойства във всяко приложение, които знаят как да говорят обратно с този сървър.

It's a bootstrap process, and each one of these apps is going to have a file called bootstrap.properties. It will contain properties just like application.properties but with a twist:

A parent Spring ApplicationContext loads the bootstrap.properties first. This is critical so that Config Server can start managing the properties in application.properties. It's this special ApplicationContext that will also decrypt any encrypted application properties.

It's smart to keep these properties files distinct.bootstrap.properties is for getting the config server ready, and application.properties is for properties specific to our application. Technically, though, it's possible to place application properties in bootstrap.properties.

Lastly, since Config Server is managing our application properties, one might wonder why have an application.properties at all? The answer is that these still come in handy as default values that perhaps Config Server doesn't have.

3. Discovery

Now that we have configuration taken care of, we need a way for all of our servers to be able to find each other. We will solve this problem by setting the Eureka discovery server up. Since our applications could be running on any ip/port combination we need a central address registry that can serve as an application address lookup.

When a new server is provisioned it will communicate with the discovery server and register its address so that others can communicate with it. This way other applications can consume this information as they make requests.

To learn more details and see a more complex discovery implementation take a look at Spring Cloud Eureka article.

3.1. Setup

Again we'll navigate to start.spring.io. Set the artifact to “discovery”. Search for “eureka server” and add that dependency. Search for “config client” and add that dependency. Finally, generate the project.

Alternatively, we can create a Spring Boot project, copy the contents of the POM from config server and swap in these dependencies:

 org.springframework.cloud spring-cloud-starter-config   org.springframework.cloud spring-cloud-starter-eureka-server 

For reference, we'll find the bundles on Maven Central (config-client, eureka-server).

3.2. Spring Config

Let's add Java config to the main class:

@SpringBootApplication @EnableEurekaServer public class DiscoveryApplication {...}

@EnableEurekaServer will configure this server as a discovery server using Netflix Eureka. Spring Boot will automatically detect the configuration dependency on the classpath and lookup the configuration from the config server.

3.3. Properties

Now we will add two properties files:

First, we add bootstrap.properties into src/main/resources:

spring.cloud.config.name=discovery spring.cloud.config.uri=//localhost:8081

These properties will let discovery server query the config server at startup.

And second, we add discovery.properties to our Git repository

spring.application.name=discovery server.port=8082 eureka.instance.hostname=localhost eureka.client.serviceUrl.defaultZone=//localhost:8082/eureka/ eureka.client.register-with-eureka=false eureka.client.fetch-registry=false

The filename must match the spring.application.name property.

In addition, we are telling this server that it is operating in the default zone, this matches the config client's region setting. We are also telling the server not to register with another discovery instance.

In production, we'd have more than one of these to provide redundancy in the event of failure and that setting would be true.

Let's commit the file to the Git repository. Otherwise, the file will not be detected.

3.4. Add Dependency to the Config Server

Add this dependency to the config server POM file:

 org.springframework.cloud spring-cloud-starter-eureka 

For reference, we can find the bundle on Maven Central (eureka-client).

Add these properties to the application.properties file in src/main/resources of the config server:

eureka.client.region = default eureka.client.registryFetchIntervalSeconds = 5 eureka.client.serviceUrl.defaultZone=//localhost:8082/eureka/

3.5. Run

Start the discovery server using the same command, mvn spring-boot:run. The output from the command line should include:

Fetching config from server at: //localhost:8081 ... Tomcat started on port(s): 8082 (http)

Stop and rerun the config service. If all is good output should look like:

DiscoveryClient_CONFIG/10.1.10.235:config:8081: registering service... Tomcat started on port(s): 8081 (http) DiscoveryClient_CONFIG/10.1.10.235:config:8081 - registration status: 204

4. Gateway

Now that we have our configuration and discovery issues resolved we still have a problem with clients accessing all of our applications.

If we leave everything in a distributed system, then we will have to manage complex CORS headers to allow cross-origin requests on clients. We can resolve this by creating a gateway server. This will act as a reverse proxy shuttling requests from clients to our back end servers.

A gateway server is an excellent application in microservice architecture as it allows all responses to originate from a single host. This will eliminate the need for CORS and give us a convenient place to handle common problems like authentication.

4.1. Setup

By now we know the drill. Navigate to //start.spring.io. Set the artifact to “gateway”. Search for “zuul” and add that dependency. Search for “config client” and add that dependency. Search for “eureka discovery” and add that dependency. Lastly, generate that project.

Alternatively, we could create a Spring Boot app with these dependencies:

 org.springframework.cloud spring-cloud-starter-config   org.springframework.cloud spring-cloud-starter-eureka   org.springframework.cloud spring-cloud-starter-zuul 

For reference, we can find the bundle on Maven Central (config-client, eureka-client, zuul).

4.2. Spring Config

Let's add the configuration to the main class:

@SpringBootApplication @EnableZuulProxy @EnableEurekaClient public class GatewayApplication {...}

4.3. Properties

Now we will add two properties files:

bootstrap.properties in src/main/resources:

spring.cloud.config.name=gateway spring.cloud.config.discovery.service-id=config spring.cloud.config.discovery.enabled=true eureka.client.serviceUrl.defaultZone=//localhost:8082/eureka/

gateway.properties in our Git repository

spring.application.name=gateway server.port=8080 eureka.client.region = default eureka.client.registryFetchIntervalSeconds = 5 zuul.routes.book-service.path=/book-service/** zuul.routes.book-service.sensitive-headers=Set-Cookie,Authorization hystrix.command.book-service.execution.isolation.thread.timeoutInMilliseconds=600000 zuul.routes.rating-service.path=/rating-service/** zuul.routes.rating-service.sensitive-headers=Set-Cookie,Authorization hystrix.command.rating-service.execution.isolation.thread.timeoutInMilliseconds=600000 zuul.routes.discovery.path=/discovery/** zuul.routes.discovery.sensitive-headers=Set-Cookie,Authorization zuul.routes.discovery.url=//localhost:8082 hystrix.command.discovery.execution.isolation.thread.timeoutInMilliseconds=600000

The zuul.routes property allows us to define an application to route certain requests based on an ant URL matcher. Our property tells Zuul to route any request that comes in on /book-service/** to an application with the spring.application.name of book-service. Zuul will then lookup the host from discovery server using the application name and forward the request to that server.

Remember to commit the changes in the repository!

4.4. Run

Run the config and discovery applications and wait until the config application has registered with the discovery server. If they are already running, we don't have to restart them. Once that is complete, run the gateway server. The gateway server should start on port 8080 and register itself with the discovery server. The output from the console should contain:

Fetching config from server at: //10.1.10.235:8081/ ... DiscoveryClient_GATEWAY/10.1.10.235:gateway:8080: registering service... DiscoveryClient_GATEWAY/10.1.10.235:gateway:8080 - registration status: 204 Tomcat started on port(s): 8080 (http)

One mistake that is easy to make is to start the server before config server has registered with Eureka. In this case, we'll see a log with this output:

Fetching config from server at: //localhost:8888

This is the default URL and port for a config server and indicates our discovery service did not have an address when the configuration request was made. Just wait a few seconds and try again, once the config server has registered with Eureka, the problem will resolve.

5. Book Service

In microservice architecture, we are free to make as many applications to meet a business objective. Often engineers will divide their services by domain. We will follow this pattern and create a book service to handle all the operations for books in our application.

5.1. Setup

One more time. Navigate to //start.spring.io. Set the artifact to “book-service”. Search for “web” and add that dependency. Search for “config client” and add that dependency. Search for “eureka discovery” and add that dependency. Generate that project.

Alternatively, add these dependencies to a project:

 org.springframework.cloud spring-cloud-starter-config   org.springframework.cloud spring-cloud-starter-eureka   org.springframework.boot spring-boot-starter-web 

For reference, we can find the bundle on Maven Central (config-client, eureka-client, web).

5.2. Spring Config

Let's modify our main class:

@SpringBootApplication @EnableEurekaClient @RestController @RequestMapping("/books") public class BookServiceApplication { public static void main(String[] args) { SpringApplication.run(BookServiceApplication.class, args); } private List bookList = Arrays.asList( new Book(1L, "Baeldung goes to the market", "Tim Schimandle"), new Book(2L, "Baeldung goes to the park", "Slavisa") ); @GetMapping("") public List findAllBooks() { return bookList; } @GetMapping("/{bookId}") public Book findBook(@PathVariable Long bookId) { return bookList.stream().filter(b -> b.getId().equals(bookId)).findFirst().orElse(null); } }

We also added a REST controller and a field set by our properties file to return a value we will set during configuration.

Let's now add the book POJO:

public class Book { private Long id; private String author; private String title; // standard getters and setters }

5.3. Properties

Now we just need to add our two properties files:

bootstrap.properties in src/main/resources:

spring.cloud.config.name=book-service spring.cloud.config.discovery.service-id=config spring.cloud.config.discovery.enabled=true eureka.client.serviceUrl.defaultZone=//localhost:8082/eureka/

book-service.properties in our Git repository:

spring.application.name=book-service server.port=8083 eureka.client.region = default eureka.client.registryFetchIntervalSeconds = 5 eureka.client.serviceUrl.defaultZone=//localhost:8082/eureka/

Let's commit the changes to the repository.

5.4. Run

Once all the other applications have started we can start the book service. The console output should look like:

DiscoveryClient_BOOK-SERVICE/10.1.10.235:book-service:8083: registering service... DiscoveryClient_BOOK-SERVICE/10.1.10.235:book-service:8083 - registration status: 204 Tomcat started on port(s): 8083 (http)

Once it is up we can use our browser to access the endpoint we just created. Navigate to //localhost:8080/book-service/books and we get back a JSON object with two books we added in out controller. Notice that we are not accessing book service directly on port 8083 but we are going through the gateway server.

6. Rating Service

Like our book service, our rating service will be a domain driven service that will handle operations related to ratings.

6.1. Setup

One more time. Navigate to //start.spring.io. Set the artifact to “rating-service”. Search for “web” and add that dependency. Search for “config client” and add that dependency. Search for eureka discovery and add that dependency. Then, generate that project.

Alternatively, add these dependencies to a project:

 org.springframework.cloud spring-cloud-starter-config   org.springframework.cloud spring-cloud-starter-eureka   org.springframework.boot spring-boot-starter-web 

For reference, we can find the bundle on Maven Central (config-client, eureka-client, web).

6.2. Spring Config

Let's modify our main class:

@SpringBootApplication @EnableEurekaClient @RestController @RequestMapping("/ratings") public class RatingServiceApplication { public static void main(String[] args) { SpringApplication.run(RatingServiceApplication.class, args); } private List ratingList = Arrays.asList( new Rating(1L, 1L, 2), new Rating(2L, 1L, 3), new Rating(3L, 2L, 4), new Rating(4L, 2L, 5) ); @GetMapping("") public List findRatingsByBookId(@RequestParam Long bookId)  bookId.equals(0L) ? Collections.EMPTY_LIST : ratingList.stream().filter(r -> r.getBookId().equals(bookId)).collect(Collectors.toList());  @GetMapping("/all") public List findAllRatings() { return ratingList; } }

We also added a REST controller and a field set by our properties file to return a value we will set during configuration.

Let's add the rating POJO:

public class Rating { private Long id; private Long bookId; private int stars; //standard getters and setters }

6.3. Properties

Now we just need to add our two properties files:

bootstrap.properties in src/main/resources:

spring.cloud.config.name=rating-service spring.cloud.config.discovery.service-id=config spring.cloud.config.discovery.enabled=true eureka.client.serviceUrl.defaultZone=//localhost:8082/eureka/

rating-service.properties in our Git repository:

spring.application.name=rating-service server.port=8084 eureka.client.region = default eureka.client.registryFetchIntervalSeconds = 5 eureka.client.serviceUrl.defaultZone=//localhost:8082/eureka/

Let's commit the changes to the repository.

6.4. Run

Once all the other applications have started we can start the rating service. The console output should look like:

DiscoveryClient_RATING-SERVICE/10.1.10.235:rating-service:8083: registering service... DiscoveryClient_RATING-SERVICE/10.1.10.235:rating-service:8083 - registration status: 204 Tomcat started on port(s): 8084 (http)

Once it is up we can use our browser to access the endpoint we just created. Navigate to //localhost:8080/rating-service/ratings/all and we get back JSON containing all our ratings. Notice that we are not accessing the rating service directly on port 8084 but we are going through the gateway server.

7. Conclusion

Сега сме в състояние да свържем различните части на Spring Cloud в работещо приложение за микросервизи. Това формира база, която можем да използваме, за да започнем да изграждаме по-сложни приложения.

Както винаги, можем да намерим този изходен код в GitHub.