获取本地服务实例方法getLocalServiceInstanc

2018-06-06  本文已影响0人  BscLiao
在使用discoveryClient.getLocalServiceInstance()时,发现该方法已经过时。源码提示使用org.springframework.cloud.client.serviceregistry.Registration,该类可以根据服务名,获取注册了该服务名的所有实例。具体使用如下的testBalance()和serviceInstance()方法。
package com.liao.web;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AController {

    private final Logger logger = Logger.getLogger(getClass());

    @Autowired
    private Registration registration; // 服务注册

    @Autowired
    private DiscoveryClient client; // 服务发现客户端

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String test(@RequestParam String param) {

        ServiceInstance instance = client.getLocalServiceInstance();
        logger.info(
                "/test, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", result:" + param);
        return "From Service-A, Param is " + param;
    }

    @RequestMapping(value = "/testBalance", method = RequestMethod.GET)
    public String testBalance(@RequestParam String param) {
        ServiceInstance instance = serviceInstance();
        String result = "/testBalance, host:port=" + instance.getUri()  + ", "
                + "service_id:" + instance.getServiceId();
        logger.info(result);
        return "From Service-A , " + result;
    }

    public ServiceInstance serviceInstance() {
        List<ServiceInstance> list = client.getInstances(registration.getServiceId());
        if (list != null && list.size() > 0) {
            for(ServiceInstance itm : list){
                if(itm.getPort() == 2001)
                    return itm;
            }   
        }
        return null;
    }

}

可以看到注入了 Registration 和 DiscoveryClient 两个对象:

上一篇下一篇

猜你喜欢

热点阅读