04-Eureka服务注册与发现

1、介绍

2、快速开始

父工程的maven 配置文件,如下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    
    <groupId>com.mindasoft</groupId>
    <artifactId>spring-cloud-eureka-parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>

    <name>feign-eureka</name>
    <description>Demo project for Spring Cloud</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <modules>
        <module>server</module>
        <module>client</module>
    </modules>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>2021.0.1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <!--skip deploy (this is just a test module) -->
                <artifactId>maven-deploy-plugin</artifactId>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
        </plugins>
    </build>


</project>

2.1、服务注册

pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mindasoft</groupId>
    <artifactId>spring-cloud-eureka-provider</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-cloud-eureka-provider</name>
    <description>Demo project for Spring Cloud</description>

    <parent>
        <groupId>com.mindasoft</groupId>
        <artifactId>spring-cloud-eureka-parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>..</relativePath> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
        <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>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.yml

spring:
  application:
    name: provider-service

server:
  port: 9001

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:9000/eureka/
  instance:
    leaseRenewalIntervalInSeconds: 10
    metadataMap:
      instanceId: ${spring.application.name}:${spring.application.instance_id:${server.port}}

启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@EnableEurekaClient     // Eureka Client 标识
@SpringBootApplication
public class EurekaHelloProviderApplication {

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

服务提供

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by huangmin 
 */
@RestController
public class HelloProvider {

    private static final Logger logger = LoggerFactory.getLogger(HelloProvider.class);

    @Value("${server.port}")
    private int port;

    @Autowired
    private Registration registration;       // 服务注册 --> EurekaRegistration

    @RequestMapping("/hello")
    public String provider() {
        return "Hello,I'm Provider!My port is :" + port + ",serviceId:" + registration.getServiceId() + " :" + registration.getInstanceId();
    }

}

2.2、服务发现

maven配置文件,与服务注册仅名称不一样,其他都是相同的。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mindasoft</groupId>
    <artifactId>spring-cloud-eureka-consumer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-cloud-eureka-consumer</name>
    <description>Demo project for Spring Cloud</description>

    <parent>
        <groupId>com.mindasoft</groupId>
        <artifactId>spring-cloud-eureka-parent</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>..</relativePath> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
        <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>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.properties

server.port=9002

# 服务注册中心地址
eureka.client.service-url.defaultZone=http://localhost:9000/eureka/

# 服务名称
spring.application.name=consumer-service

启动类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@EnableDiscoveryClient    
@SpringBootApplication
public class EurekaConsumerApplication {

      @Bean
      RestTemplate restTemplate() {
        return new RestTemplate();
    }

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

消费者

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by huangmin on 2017/11/10 14:30.
 */
@RestController
public class HelloConsumer {

	private static final Logger logger = LoggerFactory.getLogger(HelloConsumer.class);

	@Autowired
	private DiscoveryClient discoveryClient; // 服务发现客户端

	@Autowired
	private RestTemplate restTemplate; // HTTP 访问操作类

	@RequestMapping("/hello")
	public String provider() {
		ServiceInstance instance = serviceInstance();
		logger.info("provider service, host = " + instance.getHost()
				+ ", service_id = " + instance.getServiceId());
		String providerMsg = restTemplate.getForEntity(instance.getUri() + "/hello",
				String.class).getBody();
		return "Hello,I,m Consumer!discovery a provider:"+ instance.getHost() + ":" + instance.getPort()
				+ "<br/> msg from provider : <br/><br/> " + providerMsg;
	}

	/**
	 * 获取当前服务的服务实例
	 *
	 * @return ServiceInstance
	 */
	public ServiceInstance serviceInstance() {
		List<ServiceInstance> list = discoveryClient.getInstances("provider-service");
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}
}

启动后台,访问http://127.0.0.1:9002/hello,页面显示如下:

Hello,I,m Consumer!discovery a provider:localhost:9001
msg from provider :
Hello,I'm Provider!My port is :9001,serviceId:provider-service :localhost:provider-service:9001

posted @ 2022-03-02 09:51  技术那点事儿  阅读(30)  评论(0编辑  收藏  举报