1. Standalone Eureka Configuration (Without Cluster)

Had the service side

Introduction of depend on

Note the details: artifactId is spring-cloud-starter- netflix-Eureka-server if there is no starter.

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
Copy the code

The main start class

@SpringBootApplication
@EnableEurekaServer		// Start Eureka server
public class EurekaMain7001 {
    public static void main(String[] args) { SpringApplication.run(EurekaMain7001.class,args); }}Copy the code

Configuration file application.yml

server:						Port of the current module
  port: 7001

eureka:
  instance:
    hostname: localhost   # eureka server instance name
  client:
    register-with-eureka: false # Do not register yourself in the registry
    fetch-registry: false       # indicates that you are a registry and do not require retrieval services
    service-url:
      defalult-zone: http://${eureka.instance.hostname}:${server.port}/eureka/
Copy the code

Start the Spring Boot module and visit http://localhost:7001 to see the Eureka page

Eureka client

Introduction of depend on

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
Copy the code

The main start class

@SpringBootApplication
@EnableEurekaClient			// Start Eureka client
public class PaymentMain8001 {
    public static void main(String[] args) { SpringApplication.run(PaymentMain8001.class,args); }}Copy the code

Configuration file application.yml

server:
  port: 8001
spring:				
  application:
    name: cloud-payment-service		Eureka is the same name as Eureka

eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:7001/eureka
Copy the code

After the configuration is complete, go to the server page http://localhost:7001

You can see that the registration is successful

2. Configure the Eureka cluster

Cluster implementation

The rules for clustering are: register with each other

To simulate the cluster, create another Eureka module that registers with the previous Eureka server.

One uses port 7001 and the other uses port 7002.

The main configurations of both are similar (POM, main boot, etc.)

Differences from stand-alone versions

Each registered

Here in order to simulate different server cluster, first in the Windows/system32 / drivers/etc modify the hosts file:

Add two urls

The two Eureka modules register with each other

7001:

server:
  port: 7001

eureka:
  instance:
    hostname: eureka7001.com   # eureka server instance name
  client:
    register-with-eureka: false # Do not register yourself in the registry
    fetch-registry: false       # indicates that you are a registry and do not require retrieval services
    service-url:
      # register with another Eureka server
      defaultZone: http://eureka7002.com:7002/eureka/
Copy the code

7002:

server:
  port: 7002

eureka:
  instance:
    hostname: eureka7002.com
  client:
    fetch-registry: false
    register-with-eureka: false
    service-url:
      # register with another Eureka server
      defaultZone: http://eureka7001.com:7001/eureka/
Copy the code

At this point, the startup can see that the two Eurekas have registered with each other.

Client Registration

In the application. Yml file of the module that needs to be registered with Eureka, add defaultZone to the configuration of both Eureka servers in the cluster:

eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
    	Both servers are now configured in defaultZone
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
Copy the code

Once the configuration is complete, you can see that the service provider has registered two EureKas

Configuring high Availability Services (Service provider cluster)

practice

In this example, create another cloud-provider-Payment module and set port number to 8002.

The controller, service, DAO, mapper files in the project are the same as 8001 (== remember to copy them completely, otherwise it is hard to find the error ==). The only configuration that needs to be modified is server.port in the YML file

After the SERVICE is started, two cloud-payment-services have been registered

Once you’ve done this, you need to modify the code at the service invocation:

The payment_URL below is changed to the name of the Application registered in Eureka to call services on different servers of the same Application.

@RestController
public class OrderController {
    @Resource
    private RestTemplate restTemplate;

    private static final String payment_url = "http://CLOUD-PAYMENT-SERVICE";

    @GetMapping("/consumer/payment/create")
    public CommonResult<Integer> createPayment(Payment payment) {
        return restTemplate.postForObject(payment_url+"/payment/create", payment,CommonResult.class);
    }

    @GetMapping("consumer/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        return restTemplate.getForObject(payment_url+"/payment/get/"+id,CommonResult.class); }}Copy the code

But if just finish this step, the direct use of this type of url in the browser using http://localhost/consumer/payment/get/1 will be submitted to the 500 error, this is because no load balancing configuration.

To enable load balancing (default polling mode), annotate the RestTemplate with @loadBalanced.

@Configuration
public class ApplicationContextConfig {
    @Bean
    @LoadBalanced		// Enable load balancing
    public RestTemplate getRestTemplate(a) {
        return newRestTemplate(); }}Copy the code

With serverPort in the Controller code of the payment-Provider module, you can find that the service port is different each time you use the same URL:

The payment-provider helps display the code for the current service port:

public class PaymentController {

    @Resource
    private PaymentService paymentService;
	
    // Inject the port in the YML file
    @Value("${server.port}")
    private String serverPort;

    @PostMapping("/payment/create")
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);

        // You can return it with the number of the upper end, which is convenient to check whether the load balancing is really carried out during the test
        if (result == 1) {
            return new CommonResult(200."Create successful server port:"+serverPort, result);
        } else {
            return new CommonResult(444."Create failure"); }}@GetMapping("/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);

        if(payment ! =null) {
            return new CommonResult(200."Server port:"+serverPort, payment);
        } else {
            return new CommonResult(444."Query failed"); }}}Copy the code

Complete the clustering and load balancing configuration for the service provider!

Three, some details

Specification registration in microservices:

As can be seen from the previous Eureka page, Status displays host name + name + port, and the IP address of the service will not be displayed when the mouse moves to the lower left corner of the browser. In real development, yML file of each registration module can be configured to make the display more standardized and clear:

eureka:
	#... I'm going to omit that. I'm going to focus on instance over here
  instance:
    instance-id: consumer80		# Set the name in status
    prefer-ip-address: true		Set the display IP address
Copy the code

After all modules are configured, you can see that the display is clearer: