springCloud入門學習(四):Eureka元數據

Eureka元數據有兩種,分別是標準元數據和自定元數據。java

標準元數據:主機名、IP、端口號、狀態也及健康檢查等信息。這些信息會被髮布在服務註冊表中,用於服務之間的調用。web

自定義元數據:用戶自行定義的元素,遠程客戶端可訪問而且能夠根據這些元素進行必定的處理。spring


遠程客戶端獲取元數據:movie服務獲取user服務的元數據。app

一、用戶微服務修改:ide

server:
  port: 8010
spring:
  application:
    name: user
eureka:
  client:
    service-url:
      default-zone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true
    metadata-map:
      # 自定義元數據,k和v均可以隨意定義
      my-metadata: user自定義元數據

二、電影服務修改:微服務

package com.my.movie.controller;

import com.my.movie.Util.ReturnUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 垃圾美少女
 */
@RestController
@Slf4j
public class MovieController {

    @Autowired
    private DiscoveryClient discoveryClient;


    @RequestMapping(value = "/movie/getUserMetadata", method = RequestMethod.GET)
    public Map getUserMetadata(){
        try {
            List<ServiceInstance> user = discoveryClient.getInstances("user");
            return ReturnUtil.succe***esult(user,"獲取成功");
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return ReturnUtil.errorResult(null,"獲取失敗");
        }
    }
   

}


discoveryClient.getInstances(serviceId);用來獲取指定serviceId的服務的元數據。url

三、訪問 http://localhost:8020/movie/getUserMetadata server

image.png

相關文章
相關標籤/搜索