动态调用微服务

主要由三个文件组成

DynamicService.java

DynamicFeignClientFactory.java

DynamicClient.java

代码

package org.jeecg.modules.cloud.feign;

import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * Description: 通用接口,里面定义通用方法
 * 注意: 由于服务生产者所有的接口的返回值都是json格式的字符串,
 * 所以这里的通用接口的返回值最好使用String类型!!!
 */
public interface DynamicService {
    /**
     * post方法对应的方法
     *
     * @param url    服务生产者Handler方法请求映射地址
     * @param params 服务生产者Handler方法参数
     * @return
     */
    @PostMapping(value = "{url}")
    String executePostRequest(@PathVariable("url") String url, @RequestBody Object params);

    @GetMapping(value = "{url}")
    String executeGetRequest(@PathVariable("url") String url, @SpringQueryMap Object params);
}
package org.jeecg.modules.cloud.feign;

import org.springframework.cloud.openfeign.FeignClientBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * Description: FeignClient工厂类,根据服务名称创建FeignClient对象(代理对象)
 */
@Component
public class DynamicFeignClientFactory {
    private FeignClientBuilder feignClientBuilder;
    public DynamicFeignClientFactory(ApplicationContext applicationContext){
        this.feignClientBuilder = new FeignClientBuilder(applicationContext);
    }
    //动态生成feignClient对象(代理对象)
    public T getFeignClient(final Class type,String ServiceID){
        return this.feignClientBuilder.forType(type,ServiceID).build();
    }
}
package org.jeecg.modules.cloud.feign;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/*

 * Description: 通过FeignClient工厂获取到的FeignClient对象通过指定的请求去调用生产者方法!
 */
@Component
public class DynamicClient {
    @Autowired
    private DynamicFeignClientFactory dynamicDynamicFeignClientFactory;

    public Object executePostApi(String feignName, String url, Object params) {
        DynamicService dynamicService = dynamicDynamicFeignClientFactory.getFeignClient(DynamicService.class, feignName);
        return dynamicService.executePostRequest(url, params);
    }

    public Object executeGetApi(String feignName, String url, Object params) {
        DynamicService dynamicService = dynamicDynamicFeignClientFactory.getFeignClient(DynamicService.class, feignName);
        return dynamicService.executeGetRequest(url, params);
    }

}

DynamicClient 提供了两个方法 get 和 post

你可能感兴趣的:(微服务,java,spring)