springCloud入门学习(四):Eureka元数据

Eureka元数据有两种,分别是标准元数据和自定元数据。

标准元数据:主机名、IP、端口号、状态也及健康检查等信息。这些信息会被发布在服务注册表中,用于服务之间的调用。

自定义元数据:用户自行定义的元素,远程客户端可访问并且可以根据这些元素进行一定的处理。


远程客户端获取元数据:movie服务获取user服务的元数据。

1、用户微服务修改:

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自定义元数据

2、电影服务修改:

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的服务的元数据。

3、访问 http://localhost:8020/movie/getUserMetadata

image.png


猜你喜欢

转载自blog.51cto.com/13593129/2396713