2020-12-12pm 跟着狂神创建一个springcloud项目

四、将服务提供者注册到Eureka中心

1.在springcloud-provider-dept-8001的pom文件中导入Eureka依赖

		<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>

2.在8001的yml文件中添加Eureka相关配置

#Eureka[配置
eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka/

3.在8001启动类中加入注解@EnableEurekaClient

package com.buba.springcloud;

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

//启动类
@SpringBootApplication
@EnableEurekaClient //在服务启动后 自动注册到eureka中
public class DeptProvider_8001 {
   public static void main(String[] args) {
       SpringApplication.run(DeptProvider_8001.class,args);
   }
}

4.启动测试

  • 启动7001注册中心
  • 启动8001提供者

回到注册中心可以看到:
在这里插入图片描述
这就说明服务者成功的被注册到注册中心!

5,本节扩展 添加监控信息

在8001的pom文件中添加依赖

<!--actuator完善监控信息-->
   	   <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-actuator</artifactId>
       </dependency>

.在8001的yml文件中增加配置

#info配置
info:
  app.name: buba-springcloud
  company.name: https://blog.csdn.net/ShawnAndLove

注意: info是与eureka 同级!!!

  • 通过controller拿到yml配置的info信息
    在DeptController中添加以下信息:
//获取一些配置的信息,得到具体的微服务
  @Autowired
  private DiscoveryClient client;

//注册进来的微服务,获取一些信息
  @RequestMapping("/dept/discovery")
  public Object discovery(){
      //获取微服务列表的清单
      List<String> services = client.getServices();
      System.out.println("discovery=>services"+services);
      //得到一个具体的微服务信息 通过具体的微服务ID 也就是applicationName
      List<ServiceInstance> instances = client.getInstances("springcloud-provider-dept");
      for (ServiceInstance instance : instances) {
          System.out.println(
                  instance.getHost()+"\t"+
                          instance.getPort()+"\t"+
                          instance.getUri()+"\t"+
                          instance.getServiceId()
          );
      }
      return this.client;
  }
  • 在DeptProvider_8001启动类加注解@EnableDiscoveryClient
- //启动类
@SpringBootApplication
@EnableEurekaClient //在服务启动后 自动注册到eureka中
@EnableDiscoveryClient //服务发现
public class DeptProvider_8001 {
   public static void main(String[] args) {
       SpringApplication.run(DeptProvider_8001.class,args);
   }
}
  • 最后再Build项目访问localhost:8001/dept/discovery
  • 可以看到后台输出成功
  • 测试成功!

本节完

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值