Dry goods|SpringCloud-Eureka registration center, service provider and consumer

Quick view of content:

1. About the registration center, service registration, and service discovery

1 Q: Why do you need a registration center?

With the rise of the microservice framework, there are more and more service nodes, and the calls between services will become more and more dense like a spider web. Simple file configuration forms will not be able to meet the increasing call relationships, so a functionally independent, high-level The available middleman-registration center maintains the relationship between the calling and the called.

2Q: What is service registration?

The service provider writes its own information into the service list of the registration center, and the registration center will regularly monitor the above services to determine whether the service is alive, and to troubleshoot the service in time.

3 Q: What is service discovery?

Under the service governance framework, the service consumer indicates the name of the service to be called to the registration center, and the registration center obtains real access information from the service list to the service consumer. The service provider can be discovered by the service consumer, and the service consumer can actively obtain the information of the service provider.

2. About Eureka to realize service registration and service discovery

1. Features of Eureka

  • Eureka includes server-side and client-side components, both of which are developed in Java, so it is well adapted to the distributed system implemented by Java
  • Other popular development platforms also have packages for Eureka
  • Eureka provides a Restful API, and non-Java languages ​​can implement their own client programs through the API
  • Eureka is a typical AP-type registry, and the server relies on its strong consistency to provide good service instance availability. However, a typical situation of the AP is that when the cluster itself has problems, in order to ensure data consistency, it will be unable to provide external services and enter the self-protection mode. When the cluster data is synchronized and consistent, services can be provided externally.
  • The Eureka client will register its own service to the registry, and renew the contract through the service heartbeat, and can periodically pull the service list of the registry to the local, and perform periodic caching, which is convenient for the real IP call of the local service.

The following tests use the version information

java11
gradle
springboot:2.3.12.RELEASE
springcloud:Hoxton.SR12

2. Eureka Registration Center

Add dependencies:

dependencies {
    implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-server'
}

On the server main class, enable Eureka Server, @EnableEurekaServer an annotation to enable Eureka registration center mode

@EnableEurekaServer //一个注解开启Eureka注册中心模式
@SpringBootApplication
public class EurekaserverApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(EurekaserverApplication.class, args);
    }

}

Eureka Server also wants to register its own service by default, which can be closed by configuration

public class EurekaClientConfigBean{
    
    
private boolean registerWithEureka = true;
private boolean fetchRegistry = true;
...
}

The configuration in SpringBoot is as follows:

server:
  port: 8801
eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false #关闭自己注册
    fetch-registry: false #关闭拉取注册
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

After the service is started, you can see the management page of Eureka Server.
insert image description here
After the server is started, you can see the registration information of the client, and you can also view the information and status of the registered instance on the page.

 ......
2023-06-08 10:31:40.186  INFO 29553 --- [           main] DiscoveryClientOptionalArgsConfiguration : Eureka HTTP Client uses Jersey
2023-06-08 10:31:40.205  WARN 29553 --- [           main] ockingLoadBalancerClientRibbonWarnLogger : You already have RibbonLoadBalancerClient on your classpath. It will be used by default. As Spring Cloud Ribbon is in maintenance mode. We recommend switching to BlockingLoadBalancerClient instead. In order to use it, set the value of `spring.cloud.loadbalancer.ribbon.enabled` to `false` or remove spring-cloud-starter-netflix-ribbon from your project.
2023-06-08 10:31:40.256  INFO 29553 --- [           main] o.s.c.n.eureka.InstanceInfoFactory       : Setting initial instance status as: STARTING
2023-06-08 10:31:40.285  INFO 29553 --- [           main] com.netflix.discovery.DiscoveryClient    : Initializing Eureka in region us-east-1
2023-06-08 10:31:40.285  INFO 29553 --- [           main] com.netflix.discovery.DiscoveryClient    : Client configured to neither register nor query for data.
2023-06-08 10:31:40.294  INFO 29553 --- [           main] com.netflix.discovery.DiscoveryClient    : Discovery Client initialized at timestamp 1686191500293 with initial instances count: 0
2023-06-08 10:31:40.321  INFO 29553 --- [           main] c.n.eureka.DefaultEurekaServerContext    : Initializing ...
2023-06-08 10:31:40.323  WARN 29553 --- [           main] c.n.eureka.cluster.PeerEurekaNodes       : The replica size seems to be empty. Check the route 53 DNS Registry
2023-06-08 10:31:40.338  INFO 29553 --- [           main] c.n.e.registry.AbstractInstanceRegistry  : Finished initializing remote region registries. All known remote regions: []
2023-06-08 10:31:40.339  INFO 29553 --- [           main] c.n.eureka.DefaultEurekaServerContext    : Initialized
2023-06-08 10:31:40.351  INFO 29553 --- [           main] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 2 endpoint(s) beneath base path '/actuator'
2023-06-08 10:31:40.410  INFO 29553 --- [           main] o.s.c.n.e.s.EurekaServiceRegistry        : Registering application UNKNOWN with eureka with status UP
2023-06-08 10:31:40.412  INFO 29553 --- [      Thread-10] o.s.c.n.e.server.EurekaServerBootstrap   : Setting the eureka configuration..
2023-06-08 10:31:40.413  INFO 29553 --- [      Thread-10] o.s.c.n.e.server.EurekaServerBootstrap   : Eureka data center value eureka.datacenter is not set, defaulting to default
2023-06-08 10:31:40.414  INFO 29553 --- [      Thread-10] o.s.c.n.e.server.EurekaServerBootstrap   : Eureka environment value eureka.environment is not set, defaulting to test
2023-06-08 10:31:40.425  INFO 29553 --- [      Thread-10] o.s.c.n.e.server.EurekaServerBootstrap   : isAws returned false
2023-06-08 10:31:40.426  INFO 29553 --- [      Thread-10] o.s.c.n.e.server.EurekaServerBootstrap   : Initialized server context
2023-06-08 10:31:40.426  INFO 29553 --- [      Thread-10] c.n.e.r.PeerAwareInstanceRegistryImpl    : Got 1 instances from neighboring DS node
2023-06-08 10:31:40.426  INFO 29553 --- [      Thread-10] c.n.e.r.PeerAwareInstanceRegistryImpl    : Renew threshold is: 1
2023-06-08 10:31:40.426  INFO 29553 --- [      Thread-10] c.n.e.r.PeerAwareInstanceRegistryImpl    : Changing status to UP
2023-06-08 10:31:40.435  INFO 29553 --- [      Thread-10] e.s.EurekaServerInitializerConfiguration : Started Eureka Server
2023-06-08 10:31:40.446  INFO 29553 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8901 (http) with context path ''
2023-06-08 10:31:40.447  INFO 29553 --- [           main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 8901
2023-06-08 10:31:40.470  INFO 29553 --- [           main] c.l.e.EurekaserverApplication            : Started EurekaserverApplication in 3.977 seconds (JVM running for 4.644)
2023-06-08 10:39:40.450  INFO 29553 --- [a-EvictionTimer] c.n.e.registry.AbstractInstanceRegistry  : Running the evict task with compensationTime 1ms
2023-06-08 10:40:40.455  INFO 29553 --- [a-EvictionTimer] c.n.e.registry.AbstractInstanceRegistry  : Running the evict task with compensationTime 4ms
2023-06-08 10:40:43.326  INFO 29553 --- [nio-8901-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2023-06-08 10:40:43.326  INFO 29553 --- [nio-8901-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2023-06-08 10:40:43.350  INFO 29553 --- [nio-8901-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 24 ms
2023-06-08 10:40:43.651  INFO 29553 --- [nio-8901-exec-2] c.n.e.registry.AbstractInstanceRegistry  : Registered instance CLIENT1/192.168.2.180:client1:8902 with status UP (replication=false)
2023-06-08 10:41:40.336  WARN 29553 --- [eerNodesUpdater] c.n.eureka.cluster.PeerEurekaNodes       : The replica size seems to be empty. Check the route 53 DNS Registry
2023-06-08 10:41:40.459  INFO 29553 --- [a-EvictionTimer] c.n.e.registry.AbstractInstanceRegistry  : Running the evict task with compensationTime 2ms
2023-06-08 10:42:40.464  INFO 29553 --- [a-EvictionTimer] c.n.e.registry.AbstractInstanceRegistry  : Running the evict task with compensationTime 4ms

3. Eureka client

Add dependencies:

dependencies {
    implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
}

Client configuration:

server:
  port: 8902
spring:
  application:
    name: client1 #默认使用服务名称进行访问,所以必须要起一个有指向意义的服务名字
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8901/eureka/
    fetch-registry: true  #默认true
    register-with-eureka: true #默认true

On the client main class, enable service registration and discovery through the EnableDiscoveryClient annotation

@EnableDiscoveryClient
@SpringBootApplication
public class EurekaclientApplication {
    
    

    public static void main(String[] args){
    
    
        SpringApplication.run(EurekaclientApplication.class,args);
    }
}

Use DiscoveryClient to obtain service list and service instance details

@Slf4j
@RestController
@RequestMapping("test")
public class TestController {
    
    
    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/service-instances/{applicationName}")
    public List<ServiceInstance> serviceInstancesByApplicationName(@PathVariable String applicationName) {
    
    
        return this.discoveryClient.getInstances(applicationName);
    }

    @GetMapping("/discovery")
    public String discovery() {
    
    
        List<String> serviceNames = discoveryClient.getServices();
        for (String serviceName : serviceNames) {
    
    
            log.info("***** element:" + serviceName);
            List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
            for (ServiceInstance instance : instances) {
    
    
                log.info(instance.toString());
            }
        }
        return "success";
    }
}

Service instance information, including necessary information such as IP and port required for subsequent service calls

[
  {
    
    
    "uri": "http://192.168.2.180:8902",
    "metadata": {
    
    
      "management.port": "8902"
    },
    "port": 8902,
    "host": "192.168.2.180",
    "scheme": "http",
    "secure": false,
    "instanceId": "192.168.2.180:client1:8902",
    "serviceId": "CLIENT1",
    "instanceInfo": {
    
    
      "instanceId": "192.168.2.180:client1:8902",
      "app": "CLIENT1",
      "appGroupName": null,
      "ipAddr": "192.168.2.180",
      "sid": "na",
      "homePageUrl": "http://192.168.2.180:8902/",
      "statusPageUrl": "http://192.168.2.180:8902/actuator/info",
      "healthCheckUrl": "http://192.168.2.180:8902/actuator/health",
      "secureHealthCheckUrl": null,
      "vipAddress": "client1",
      "secureVipAddress": "client1",
      "countryId": 1,
      "dataCenterInfo": {
    
    
        "@class": "com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo",
        "name": "MyOwn"
      },
      "hostName": "192.168.2.180",
      "status": "UP",
      "overriddenStatus": "UNKNOWN",
      "leaseInfo": {
    
    
        "renewalIntervalInSecs": 30,
        "durationInSecs": 90,
        "registrationTimestamp": 1686192043567,
        "lastRenewalTimestamp": 1686192193487,
        "evictionTimestamp": 0,
        "serviceUpTimestamp": 1686192043567
      },
      "isCoordinatingDiscoveryServer": false,
      "metadata": {
    
    
        "management.port": "8902"
      },
      "lastUpdatedTimestamp": 1686192043568,
      "lastDirtyTimestamp": 1686192043464,
      "actionType": "ADDED",
      "asgName": null
    }
  }
]

After the client is started, you can see the log of the client's active registration

.......
2023-06-08 10:40:42.607  INFO 29923 --- [           main] DiscoveryClientOptionalArgsConfiguration : Eureka HTTP Client uses Jersey
2023-06-08 10:40:42.664  WARN 29923 --- [           main] ockingLoadBalancerClientRibbonWarnLogger : You already have RibbonLoadBalancerClient on your classpath. It will be used by default. As Spring Cloud Ribbon is in maintenance mode. We recommend switching to BlockingLoadBalancerClient instead. In order to use it, set the value of `spring.cloud.loadbalancer.ribbon.enabled` to `false` or remove spring-cloud-starter-netflix-ribbon from your project.
2023-06-08 10:40:42.750  INFO 29923 --- [           main] o.s.c.n.eureka.InstanceInfoFactory       : Setting initial instance status as: STARTING
2023-06-08 10:40:42.782  INFO 29923 --- [           main] com.netflix.discovery.DiscoveryClient    : Initializing Eureka in region us-east-1
2023-06-08 10:40:42.935  INFO 29923 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON encoding codec LegacyJacksonJson
2023-06-08 10:40:42.935  INFO 29923 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON decoding codec LegacyJacksonJson
2023-06-08 10:40:43.056  INFO 29923 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using XML encoding codec XStreamXml
2023-06-08 10:40:43.056  INFO 29923 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using XML decoding codec XStreamXml
2023-06-08 10:40:43.144  INFO 29923 --- [           main] c.n.d.s.r.aws.ConfigClusterResolver      : Resolving eureka endpoints via configuration
2023-06-08 10:40:43.161  INFO 29923 --- [           main] com.netflix.discovery.DiscoveryClient    : Disable delta property : false
2023-06-08 10:40:43.161  INFO 29923 --- [           main] com.netflix.discovery.DiscoveryClient    : Single vip registry refresh property : null
2023-06-08 10:40:43.161  INFO 29923 --- [           main] com.netflix.discovery.DiscoveryClient    : Force full registry fetch : false
2023-06-08 10:40:43.161  INFO 29923 --- [           main] com.netflix.discovery.DiscoveryClient    : Application is null : false
2023-06-08 10:40:43.161  INFO 29923 --- [           main] com.netflix.discovery.DiscoveryClient    : Registered Applications size is zero : true
2023-06-08 10:40:43.161  INFO 29923 --- [           main] com.netflix.discovery.DiscoveryClient    : Application version is -1: true
2023-06-08 10:40:43.161  INFO 29923 --- [           main] com.netflix.discovery.DiscoveryClient    : Getting all instance registry info from the eureka server
2023-06-08 10:40:43.457  INFO 29923 --- [           main] com.netflix.discovery.DiscoveryClient    : The response status is 200
2023-06-08 10:40:43.458  INFO 29923 --- [           main] com.netflix.discovery.DiscoveryClient    : Starting heartbeat executor: renew interval is: 30
2023-06-08 10:40:43.460  INFO 29923 --- [           main] c.n.discovery.InstanceInfoReplicator     : InstanceInfoReplicator onDemand update allowed rate per min is 4
2023-06-08 10:40:43.463  INFO 29923 --- [           main] com.netflix.discovery.DiscoveryClient    : Discovery Client initialized at timestamp 1686192043462 with initial instances count: 0
2023-06-08 10:40:43.464  INFO 29923 --- [           main] o.s.c.n.e.s.EurekaServiceRegistry        : Registering application CLIENT1 with eureka with status UP
2023-06-08 10:40:43.464  INFO 29923 --- [           main] com.netflix.discovery.DiscoveryClient    : Saw local status change event StatusChangeEvent [timestamp=1686192043464, current=UP, previous=STARTING]
2023-06-08 10:40:43.466  INFO 29923 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_CLIENT1/192.168.2.180:client1:8902: registering service...
2023-06-08 10:40:43.492  INFO 29923 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8902 (http) with context path ''
2023-06-08 10:40:43.493  INFO 29923 --- [           main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 8902
2023-06-08 10:40:43.504  INFO 29923 --- [           main] c.l.e.EurekaclientApplication            : Started EurekaclientApplication in 2.806 seconds (JVM running for 4.028)
2023-06-08 10:40:43.653  INFO 29923 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_CLIENT1/192.168.2.180:client1:8902 - registration status: 204
2023-06-08 10:41:13.464  INFO 29923 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : Disable delta property : false
2023-06-08 10:41:13.464  INFO 29923 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : Single vip registry refresh property : null
2023-06-08 10:41:13.464  INFO 29923 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : Force full registry fetch : false
2023-06-08 10:41:13.465  INFO 29923 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : Application is null : false
2023-06-08 10:41:13.465  INFO 29923 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : Registered Applications size is zero : true
2023-06-08 10:41:13.465  INFO 29923 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : Application version is -1: false
2023-06-08 10:41:13.465  INFO 29923 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : Getting all instance registry info from the eureka server
2023-06-08 10:41:13.515  INFO 29923 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : The response status is 200
2023-06-08 10:41:54.752  INFO 29923 --- [nio-8902-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2023-06-08 10:41:54.752  INFO 29923 --- [nio-8902-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2023-06-08 10:41:54.758  INFO 29923 --- [nio-8902-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 6 ms
2023-06-08 10:42:07.625  INFO 29923 --- [nio-8902-exec-3] c.l.e.controller.TestController          : ***** element:client1
2023-06-08 10:42:07.628  INFO 29923 --- [nio-8902-exec-3] c.l.e.controller.TestController          : [EurekaDiscoveryClient.EurekaServiceInstance@64ca6245 instance = InstanceInfo [instanceId = 192.168.2.180:client1:8902, appName = CLIENT1, hostName = 192.168.2.180, status = UP, ipAddr = 192.168.2.180, port = 8902, securePort = 443, dataCenterInfo = com.netflix.appinfo.MyDataCenterInfo@5288f575]

The default is to use appname, which requires spring.application.name to be configured. If you do not want to use appname to access services, you can configure to use IP.

eureka:
  instance:
    prefer-ip-address: true #强制使用IP

The above is the construction process of the most basic service registry and service provider. A service registry can be started, a service client can be started, the client can register itself with the registry, and can obtain the service list on the registry.

In addition, there is a highly available version of the service registration center, that is, two or more eurekaserver nodes, they register with each other, service providers can register their own information with the two nodes, any service registration node downtime will not affect each service calls between nodes.

And service consumers request load balancing strategies between multiple service providers, relying on Ribbon to achieve.

Guess you like

Origin blog.csdn.net/c_zyer/article/details/131104642