preface

Service governance

With the development of services, the number of micro-service applications increases. It becomes more and more difficult to manage and manage these services, and the cluster scale, service location, and service name will change. Manual maintenance is prone to errors or naming conflicts. Service governance is just to solve this problem. Service governance is the most core and basic module in microservice architecture, which mainly realizes the automatic registration and discovery of each microservice instance.

The service registry

In a service governance framework, one or more service registries are built.

Each service module registers its services to the registry, informs the registry of host host, port number, version number, communication protocol and other additional information, and the registry classifies the service list according to the service name.

The service registry also needs to monitor whether the services in the list are available by heartbeat. If they are not available, they need to be removed from the list of services to achieve the effect of troubleshooting services.

Service discovery

Interservice invocations are no longer implemented by specifying a specific instance address, but by making a request invocation to the service name.

Service callers need to get a list of instances of all services from the service registry before they can access specific service instances.

When a service caller invokes a call, it takes out a specific service instance with some policy for a service invocation (client load balancing).

In production environments, for performance reasons, services are not fetched from the service registry every time, and different application scenarios use different implementation strategies for caching and service culling mechanisms.

Spring Cloud Eureka

Spring Cloud Eureka is based on Netflix Eureka to realize service registration and discovery. It mainly consists of two components:

  • Eureka Server (Server) : Service registry. It supports high availability configuration and provides good service instance availability based on strong consistency. Service registries can copy their state to each other in asynchronous mode.
  • Eureka Client: Processing service registration and discovery, the client can be implemented by means of annotation and parameters configuration register and found that the client to the services provided by the registry itself and periodically sends a heartbeat to update the service agreement, it had been the client from the server query the current registration service information and put them to the local cache and periodic refreshes the service status.

Eureka infrastructure

  • Service Registry (Eureka Server) : A Server that provides service registration and discovery functions.
  • Service Provider: An application that provides services registers its services with the Eureka Server for other applications to discover.
  • Service Consumer: The Consumer application retrieves a list of services from Eureka Server and invokes the corresponding Service (Ribbon or Feign).

Infrastructure diagram

Rapid Establishment of Service Registry (Eureka Server)

1. Create a Spring Boot project and add dependencies

< properties > < Java version > 1.8 < / Java version > < spring - cloud. Version > Hoxton. RELEASE < / spring - cloud. Version > < / properties > <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>${spring-cloud.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>
Copy the code

2. @enableeurekaserver annotation starts the service registry

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

3. Configure the application.properties file

server.port=9999
#eurekaEureka. The instance. The hostname = 127.0.0.1 eureka. The client. The register - with - eureka =false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
Copy the code
  • Register-with-eureka: The current application is a service registry. If the value is set to false, the application does not register with the registry.
  • Eureka.client.fetch -registry: The registry is responsible for maintaining service instances, so set to false to not retrieve the currently applied service.
  • Eureka. Client. ServiceUrl. DefaultZone: used to interact with eureka Server address, registration services and discover services need to rely on this address.

4. Start the application and access:http://127.0.0.1:9999/

Instances Currently Registered with Eureka list shows No Instances available, indicating that the registry has not registered any services.

Service Provider

1. Create a Spring Boot project and add dependencies

< properties > < Java version > 1.8 < / Java version > < spring - cloud. Version > Hoxton. RELEASE < / spring - cloud. Version > < / properties > <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>${spring-cloud.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>
Copy the code

2. The @enableDiscoveryClient annotation starts the Eureka client

@springBootApplication // @enableEurekaclient This annotation is used when eureka is used as the registry, Scene is relatively single @ EnableDiscoveryClient / / scene wider public class SpringCloudEurekaServiceApplication {public static void main(String[] args) { SpringApplication.run(SpringCloudEurekaServiceApplication.class, args); }}Copy the code

@enableeurekaclient and @EnableDiscoveryClient work just as well in the current example. The @enableEurekaclient annotation is used when Eureka is used as the registry in a single scenario. The @enableDiscoveryClient scenario is more extensive.

3. Configure the application.properties file

server.port=8888
spring.application.name=spring-cloud-eureka-service
#info Application informationInfo. App. Name = spring - the cloud - eureka - service info. The app. The version = v1.0.0 info. The app. The description = spring - the cloud - eureka - service#eurekaEureka. The instance. The hostname = 127.0.0.1Heartbeat every 5s to prove that the service is still alive
eureka.instance.lease-renewal-interval-in-seconds=5
If there is no heartbeat within 10 seconds, this service will be removed from the servereureka.instance.lease-expiration-duration-in-seconds=10 Eureka. Client. ServiceUrl defaultZone = http://127.0.0.1:9999/eureka/Copy the code
  • Eureka.instance. lease-renewal- interval-seconds: specifies the heartbeat interval
  • Eureka. Instance. lease-expiration- durations-in-seconds: if no heartbeat is detected within seconds, the service is deleted

4. Start the application and access:http://127.0.0.1:9999/

In the console of the service registry we can see the following output indicating that the service was successfully registered.

c.n.e.registry.AbstractInstanceRegistry : Registered instance SPRING - CLOUD - EUREKA - SERVICE / 192.168.101.201: SPRING -- CLOUD - EUREKA - SERVICE: 8888 with the status UP (replication=false)
Copy the code

In the Eureka information panel, you can also see the service registration information in the Instances Currently Registered with Eureka list. The diagram below:

High Availability Registry (Cluster)

The single-node mode of service registry was described above, although this mode is not usually adopted in a real production environment. In distributed systems, service registries are a very important part of the system, and in single-node mode, failure can be devastating. So in order to maintain high availability of services, a clustered solution is often used.

In Eureka’s service governance design, all nodes are both service providers and service consumers, and service registries are no exception. Eureka registers services with each other to synchronize service lists and achieve high availability.

A two-node registry

  1. Set up service registry A, and the configuration file is as follows:
server.port=9991
spring.application.name=eureka-server
spring.profiles.active=nodea
#eureka
eureka.instance.hostname=nodea
# set microservice invocation address to IP first (default: false)
#eureka.instance.prefer-ip-address=true
eureka.client.serviceUrl.defaultZone=http://nodeb:9992/eureka/
Copy the code
  1. Set up service registry B with the following configuration files:
server.port=9992
spring.application.name=eureka-server
spring.profiles.active=nodeb
#eureka
eureka.instance.hostname=nodeb
# set microservice invocation address to IP first (default: false)
#eureka.instance.prefer-ip-address=true
eureka.client.serviceUrl.defaultZone=http://nodea:9991/eureka/
Copy the code
  1. Add the conversion between nodeA and nodeb in /etc/hosts (directory C:\Windows\System32\drivers\etc\hosts on Windows) as follows:
127.0.0.1 nodea
127.0.0.1 nodeb
Copy the code
  1. Start two projects, accessed separatelyhttp://nodea:9991/andhttp://nodeb:9992/, we can see that both nodes have been registered, as shown in the following figure:

eureka.client.serviceUrl.defaultZone=http://nodea:9991/eureka/,http://nodeb:9992/eureka/
Copy the code

After starting the project, we visit the two service registries and see that the services are registered in these two nodes.

Service Consumer

Use the Ribbon to invoke services

1. Configure POM dependencies
< properties > < Java version > 1.8 < / Java version > < spring - cloud. Version > Hoxton. RELEASE < / spring - cloud. Version > < / properties > <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

Copy the code
2. Configure the application.properties file
spring.application.name=spring-cloud-ribbon-consumer
server.port=8081
eureka.client.serviceUrl.defaultZone=http://nodea:9991/eureka/,http://nodeb:9992/eureka/
Copy the code
3. Enable the class configuration

Register the application as a Eureka client with the @enableDiscoveryClient annotation to obtain service discovery capability.

Create a Spring Bean instance of the RestTemplate to invoke the service.

Enable load balancing on the client side with the @loadBalanced annotation.

@SpringBootApplication
@EnableDiscoveryClient
public class SpringCloudRibbonConsumerApplication {

	@Bean
	@LoadBalanced
	RestTemplate restTemplate() {returnnew RestTemplate(); } public static void main(String[] args) { SpringApplication.run(SpringCloudRibbonConsumerApplication.class, args); }}Copy the code
4. ConsumerController implements the service invocation
@RestController
public class ConsumerController {

	@Autowired
	RestTemplate restTemplate;
	
	@RequestMapping("/test")
	public String test() {
		return restTemplate.getForEntity("http://spring-cloud-eureka-service/test", String.class).getBody(); }}Copy the code

Spring-cloud-eureka-service indicates the application name of the service registry. It is case-sensitive.

Use Feign to invoke the service

1. Configure POM dependencies
< properties > < Java version > 1.8 < / Java version > < spring - cloud. Version > Hoxton. RELEASE < / spring - cloud. Version > < / properties > <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>
Copy the code
2. Configure the application.properties file
spring.application.name=spring-cloud-feign-consumer
server.port=8080
eureka.client.serviceUrl.defaultZone=http://nodea:9991/eureka/,http://nodeb:9992/eureka/
Copy the code
3. Enable the class configuration

Register the application as a Eureka client with the @enableDiscoveryClient annotation to obtain service discovery capability.

Enable feign to make remote calls via the @enableFeignClients annotation.

@springBootApplication @enableDiscoveryClient // Enable service registration and discovery @enableFeignClients // EnableFeign to make remote calls to public class SpringCloudFeignConsumerApplication { public static void main(String[] args) { SpringApplication.run(SpringCloudFeignConsumerApplication.class, args); }}Copy the code
4. Implement the service invocation interface
@FeignClient(name = "spring-cloud-eureka-service")
public interface TestService {

	@RequestMapping("/test")
	public String test(a); }Copy the code

Spring-cloud-eureka-service indicates the application name of the service registry. It is case-sensitive.

The method names and parameters in this interface must be the same as those in contoller in the remote service.

5. ConsumerController implements the service invocation
@RestController
public class ConsumerController {

	@Autowired
	private TestService testService;
	
	@RequestMapping("/test")
	public String test() {
		return testService.test(); }}Copy the code

The sample code

github

Yards cloud

The copyright of this article belongs to Chaowu And Qinghan, please indicate the source.

Spring Cloud (II) : Eureka Service Registry

The original address: https://www.zwqh.top/article/info/28

If the article is not enough, welcome to make suggestions, the follow-up will improve ~

If this article is helpful to you, please give me a thumbs up

Pay attention to my public number, the article continues to update…