Eureka服務註冊與獲取

一、Eureka服務註冊

註冊服務,就是在服務上添加Eureka的客戶端依賴,客戶端代碼會自動把服務註冊到EurekaServer中。

修改itcast-service-provider工程

  1. 在pom.xml中,添加springcloud的相關依賴。
  2. 在application.yml中,添加springcloud的相關依賴。
  3. 在引導類上添加註解,把服務注入到eureka註冊中心。

具體操作

1、pom.xml

參照itcast-eureka,先添加SpringCloud依賴:

<!-- SpringCloud的依賴 -->
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Finchley.SR2</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

然後是Eureka客戶端:

<!-- Eureka客戶端 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

2、application.yml

server:
  port: 8081
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/heima
    username: root
    password: root
    driverClassName: com.mysql.jdbc.Driver
  application:
    name: service-provider # 應用名稱,註冊到eureka後的服務名稱
mybatis:
  type-aliases-package: cn.itcast.service.pojo
eureka:
  client:
    service-url: # EurekaServer地址
      defaultZone: http://127.0.0.1:10086/eureka

注意:

  • 這裏我們添加了spring.application.name屬性來指定應用名稱,將來會作爲應用的id使用。

3、引導類

在引導類上開啓Eureka客戶端功能

通過添加@EnableDiscoveryClient來開啓Eureka客戶端功能

@SpringBootApplication
@EnableDiscoveryClient
public class ItcastServiceProviderApplication {

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

4、重啓項目,訪問Eureka監控頁面查看

在這裏插入圖片描述

二、Eureka服務獲取

接下來我們修改itcast-service-consumer,嘗試從EurekaServer獲取服務。

方法與消費者類似,只需要在項目中添加EurekaClient依賴,就可以通過服務名稱來獲取信息了!

1、修改UserController代碼

用DiscoveryClient類的方法,根據服務名稱,獲取服務實例:

@Controller
@RequestMapping("consumer/user")
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient; // eureka客戶端,可以獲取到eureka中服務的信息

    @GetMapping
    @ResponseBody
    public User queryUserById(@RequestParam("id") Long id){
        // 根據服務名稱,獲取服務實例。有可能是集羣,所以是service實例集合
        List<ServiceInstance> instances = discoveryClient.getInstances("service-provider");
        // 因爲只有一個Service-provider。所以獲取第一個實例
        ServiceInstance instance = instances.get(0);
        // 獲取ip和端口信息,拼接成服務地址
        String baseUrl = "http://" + instance.getHost() + ":" + instance.getPort() + "/user/" + id;
        User user = this.restTemplate.getForObject(baseUrl, User.class);
        return user;
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章