Getting started with springCloud: Eureka metadata

There are two kinds of Eureka metadata: standard metadata and custom metadata.

Standard metadata: host name, IP, port number, status, health check and other information. This information is published in the service registry for calls between services.

Custom metadata: user-defined elements that can be accessed by remote clients and processed according to these elements.


Remote client gets metadata: the movie service gets metadata of the user service.

1. User microservice modification:

server:
  port: 8010
spring:
  application:
    name: user
eureka:
  client:
    service-url:
      default-zone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true
    metadata-map:
      #Custom metadata, k and v can be defined at will
      my-metadata: user user-defined metadata 

2. Modification of film service:

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 Garbage Girl
 */
@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,"Get success");
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return ReturnUtil.errorResult(null,"Acquisition failure");
        }
    }
   

}


discoveryClient.getInstances(serviceId); used to get the metadata of the service with the specified serviceId.

3. Visit http://localhost:8020/movie/getUserMetadata


Tags: Java Spring Lombok

Posted on Fri, 08 Nov 2019 15:55:19 -0500 by dionsweet