虽然说是服务的提供者,但其实也可能是消费者,因为在微服务的项目中,各个微服务都是可以互相访问对外公开的api的。

    打开idea,同样的,在eureka目录下再建一个module:erueka-client(名称随意)

    然后是添加pom依赖:

    1. <dependencies>
    2. <dependency>
    3. <groupId>org.springframework.cloud</groupId>
    4. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    5. </dependency>
    6. ## 因为是web工程,所以还需引入SpringBootWeb的依赖
    7. <dependency>
    8. <groupId>org.springframework.boot</groupId>
    9. <artifactId>spring-boot-starter-web</artifactId>
    10. </dependency>
    11. </dependencies>

    编写application.yml文件:

    1. spring:
    2. application:
    3. name: eureka-client # 告诉注册中心,我的名字
    4. server:
    5. port: 30000 # 告诉注册中心,我的端口号
    6. eureka:
    7. client:
    8. service-url:
    9. defaultZone: http://localhost:20000/eureka #注册中心的地址
    10. instance:
    11. lease-renewal-interval-in-seconds: 5 # 每隔5秒钟向服务中心发起续约请求
    12. lease-expiration-duration-in-seconds: 30 # 如果30秒内依然没有服务续约请求,判定服务过期(服务剔除)

    编写启动类:

    1. @SpringBootApplication
    2. @EnableDiscoveryClient //到注册中心拉取服务注册列表
    3. public class EurekaClientApplication {
    4. public static void main(String[] args) {
    5. new SpringApplicationBuilder(EurekaClientApplication.class)
    6. .web(WebApplicationType.SERVLET)
    7. .run(args);
    8. }
    9. }

    既然是服务的提供者,那么就需要提供一些对外暴露的接口,就写一个Controller吧,里面有一个sayhi的方法

    1. @RestController
    2. @Slf4j
    3. public class Controller {
    4. @Value("${server.port}")
    5. private Integer port;
    6. @GetMapping("/say-hi")
    7. public String sayHi() {
    8. return "This is" + port;
    9. }
    10. }

    接口很简单,就返回一个字符串,返回这个服务的端口号

    然后就启动项目,访问:localhost:30000/say-hi,看看浏览器上是否打印出了: This is 30000