SpringCloud服务注册与发现Eureka

项目实战

服务注册中心 :eureka-server服务注册中心提供服务注册功能

服务提供方:eureka-service注册服务到服务注册中心

项目结构

项目使用maven管理项目,建立多模块项目

SpringCloud | 1.微服务的注册与发现(Eureka)_提供方
project

一、服务注册中心:eureka-server

核心依赖
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>
实现服务注册中心

实现一个服务注册中心的功能非常简单,只需要在启动类EurekaServer上使用@EnableEurekaServer注解

@EnableEurekaServer
@SpringBootApplication
public class EurekaServer {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServer.class,args);
    }
}
配置文件

默认情况下,该服务注册中心也会将自己作为客户端来尝试注册它自己,所以我们需要禁用它的客户端注册行为,只需要在application.yml配置文件中增加如下信息

spring:
  application:
    name: eureka-server
# 端口号
server:
  port: 8000
# eureka配置
eureka:
  client:
    register-with-eureka: false #是否将自己注册到Eureka Server,默认为true。
    fetch-registry: false #是否从Eureka Server获取注册信息,默认为true
    serviceUrl:
      #设置与Eureka Server交互的地址,查询服务和注册服务都需要依赖这个地址。
      #默认是http://localhost:8761/eureka ;多个地址可使用 , 分隔。
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
  instance:
    hostname: localhost
启动项目

启动EurekaServer,访问http://localhost:8000/可以看到Eureka的页面,从红框的位置可以看到没有任务服务实例注册到当前的服务注册中心

SpringCloud | 1.微服务的注册与发现(Eureka)_Java_02
Eureka

二、服务提供方 :eureka-service

每一个实例注册之后需要向注册中心发送心跳,当clientserver注册时,它会提供一些元数据,例如主机和端口,URL,主页等。Eureka server 从每个client实例接收心跳消息。 如果心跳超时,则通常将该实例从注册server中删除。

核心依赖
    <dependencies>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
    </dependencies>
实现服务提供方

实现一个服务提供方也很简单,只要在项目的启动类EurekaService {上使用@EnableEurekaClient注解即可

@EnableEurekaClient
@SpringBootApplication
public class EurekaService {
    public static void main(String[] args) {
        SpringApplication.run(EurekaService.class,args);
    }
}
配置文件
spring:
  application:
    name: eureka-service
# 端口号
server:
  port: 8001
# eureka配置
eureka:
  client:
    serviceUrl:
      #应服务注册中心的配置内容,指定服务注册中心的位置。
      defaultZone: http://${eureka.instance.hostname}:8000/eureka/ 
  instance:
    hostname: localhost
启动项目

启动EurekaService,访问 http://localhost:8000/`可以看到Eureka的页面

SpringCloud | 1.微服务的注册与发现(Eureka)_spring_03
新建EurekaServiceApi
@RestController
public class EurekaServiceApi {
    private final Logger logger = LoggerFactory.getLogger(EurekaServiceApi.class);
    @Autowired
    private DiscoveryClient client;
    @RequestMapping(value = "/add",method=RequestMethod.GET)
    public Integer add(@RequestParam Integer a ,@RequestParam Integer b){
        Integer c = a+b;
        logger.info( "client services:"+client.getServices());
        return c;
    }
 
}

Console输出

SpringCloud | 1.微服务的注册与发现(Eureka)_提供方_04

项目源码

码云tag v0.1

SpringCloud | 1.微服务的注册与发现(Eureka)_Java_05