Codementor Events

Microservices and Cloud Configuration using Spring Boot

Published Sep 28, 2019

Now that we have the config-server, eureka-server-registry and the github repository configuration.repository for the configurations, we can start creating the first microservice, this microservice will handle the customers data. Like the previous project we need to create a new project from start.spring.io with next dependencies:

  • H2 Database
  • Spring Web
  • Config Client
  • Spring Data JPA
  • Eureka Client

With the previous dependencies we can create the REST endpoints required:

POST /customers
GET  /customers

This microservice will have an endpoint to create a new customer and a second endpoint to fetch all the customers created

Git repo

if you want to test the results here is the repository
customer-ms

Access to the config server

The first thing we need to do, is conect the microservice to the configuration server and fetch the configurations when the microservices creates the application context, in order to do this let's add next lines to bootstrap.yml:

spring:
  application:
    name: customer
  cloud:
    config:
      uri: http://localhost:8081

The properties that needs to be set are: spring.application.name and spring.cloud.config.uri, the first one it is in this case the name of the file from the master branch in the git repository, and the second one is the location of the spring configuration server, remember we are using 8081 port.
Those are all the configuration we need for now, you can point to a particular branch in the git repository for instance, to know more about the configuration you may want to review the spring docs.

Enable eureka client

Let's add new entries in the file customer.yml located in the master branch of the git repository

eureka:
  client:
    eureka-server-u-r-l-context: http://localhost:8082/eureka
    service-url:
      defaultZone: http://localhost:8082/eureka

Now the microservice will connect to eureka server registry,
I've added next entry:

application:
  welcome:
    message: This is an example

we are going to show this message in the log when we are creating a new customer.

Create customers endpoint

1.- Create a java entity to save new customer with properties: id, name

//Customer.java
@Entity
@Table(name="customer")
public class Customer {
    @Id
    private String uuid;
    private String name;
  // getter and setter methods
}

2.- Create a new Repository

public interface CustomerRepository extends
        JpaRepository<Customer, String> {
}

3.- Create a controller with @PostMapping and @GetMapping
In the next code snippet we can see the property helloMessage that will be injected from the git repository and shown in the application log

@RestController
@RequestMapping("/customers")
public class CustomerController {

    private CustomerRepository customerRepository;

    @Value("${application.welcome.message}")
    private String helloMessage;

    private final Logger log = LoggerFactory.getLogger(CustomerController.class);

    public CustomerController(CustomerRepository customerRepository) {
        this.customerRepository = customerRepository;
    }

    @PostMapping
    public HttpEntity<Customer> createCustomer(
            @RequestBody Customer customer
    ){
        log.info(helloMessage);
        this.customerRepository.saveAndFlush(customer);
        return new ResponseEntity<>(customer, HttpStatus.OK);
    }

    @GetMapping
    public HttpEntity<List<Customer>> findAll() {
        log.info(helloMessage);
        return new ResponseEntity<>(this.customerRepository.findAll(),
                HttpStatus.OK);
    }
}

Test application

In order to test the microservice you must run all the spring applications: server config, eureka server and customer microservice.
Here are the steps to create the application context:
1.- Connect to spring server config and fetch configurations using : application name and spring cloud config uri
uno.png
2.- Based on the configurations spring server will return the configurations from https://github.com/VCGDEV/application-configs.git/customer.yml

2019-09-27 20:24:32 INFO  o.s.c.c.c.ConfigServicePropertySourceLocator:151 - Located environment: name=customer, profiles=[default], label=null, version=d81dfaf847f8341cf09d45397f1998adede6eca5, state=null
2019-09-27 20:24:32 INFO  o.s.c.b.c.PropertySourceBootstrapConfiguration:101 - Located property source: CompositePropertySource {name='configService', propertySources=[MapPropertySource {name='configClient'}, MapPropertySource {name='https://github.com/VCGDEV/application-configs.git/customer.yml'}]}

3.- The configurations for port, eureka, application.welcome.message and database will be used for the IOC to create and inject the required objects.
4.- Application will be registered to eureka server

2019-09-27 20:24:41 INFO  o.s.c.n.e.s.EurekaServiceRegistry:41 - Registering application CUSTOMER with eureka with status UP
2019-09-27 20:24:41 INFO  c.n.d.DiscoveryClient:844 - DiscoveryClient_CUSTOMER/192.168.8.105:customer:8083: registering service...
2019-09-27 20:24:41 INFO  c.n.d.DiscoveryClient:853 - DiscoveryClient_CUSTOMER/192.168.8.105:customer:8083 - registration status: 204

And if you go to the eureka instance:
eureka.png
As you can see our application is listed in the instance resgistered with the ip and local port, this will be used by the gateway to redirec the traffic to the microservice.

Now I'll hit the endpoints

POST endpoint

post.png

GET endpoint

get.png

and the log every time the endpoints are hitten
![log.png](https://ucarecdn.com/07c17a65-d081-46cd-a6d1-4289c0b96b69

Finally we are using a microservice architecture: config server, eureka server, centralized configuration and a customer service, a gateway will be created in the future.

Thanks for reading and please, write a feedback

Discover and read more posts from Victor de la Cruz
get started