feign动态调用远程服务

前言

第三方支付时传callbackURL过来,回调时使用feign
同事写的代码,感觉不错,摘录一下

正文

CustomFeign

import feign.HeaderMap;
import feign.RequestLine;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;

import java.net.URI;
import java.util.Map;


@FeignClient(value = "custom-feign")
public interface CustomFeign {

    @RequestLine("POST")
    String postRequest(URI baseUri, @HeaderMap Map<String, Object> headerMap, @RequestBody String request);

    @RequestLine("GET")
    String getRequest(URI baseUri, @HeaderMap Map<String, Object> headerMap, @RequestBody String request);

}

FeignClientService

import feign.Feign;
import feign.Retryer;
import feign.Target;
import feign.codec.Decoder;
import feign.codec.Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClientsConfiguration;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;

/**
 *
 */
@Component
@Import(FeignClientsConfiguration.class)
public class FeignClientService {

    private CustomFeign customFeign;

    @Autowired
    public FeignClientService(Decoder decoder, Encoder encoder) {
        customFeign = Feign.builder().encoder(encoder).decoder(decoder)
                .retryer(Retryer.NEVER_RETRY)
                .target(Target.EmptyTarget.create(CustomFeign.class));
    }

    /**
     * 执行调用方法
     *
     * @return s
     */
    public String postExecute(String url, Map<String, Object> header, String content) {
        try {
            return customFeign.postRequest(new URI(url), header, content);
        } catch (URISyntaxException e) {
            e.printStackTrace();
            //
        }
        return null;
    }

}

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