SpringBoot动态创建FeignClient,根据Eureka服务名调用服务

本文基于SpringCloud,使用的前提是客户端要与服务端注册到相同的eureka上,同时项目(SpringCloud)整合HttpServlet,通过HttpServlet自定义对外接口

导入SpringCloud的opnefeign的pom依赖
        
            org.springframework.cloud
            spring-cloud-starter-openfeign
        
自定义 HTTP Servlet(服务端提供接口)
  • 首先写一个类 继承 HttpServlet 并重写里面的方法
public class PersonController extends HttpServlet {
     /**
      * get方法
      * @param request
      * @param response
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //get方法
    }
    
    /**
     * post方法
     * @param request
     * @param response
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //读取请求的Body
        String s = ReadAsChars2(request);
        System.out.println("body内容:",s);
    }

    /**
     * 读取请求body
     * @param request
     * @return
     */
    private String ReadAsChars2(HttpServletRequest request) {
        InputStream is = null;
        StringBuilder sb = new StringBuilder();
        try {
            is = request.getInputStream();

            byte[] b = new byte[4096];
            for (int n; (n = is.read(b)) != -1; ) {
                sb.append(new String(b, 0, n));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }
}
  • 其次 在SpringBoot项目中 自定义Configuration,指定接口的路径
public class PersonBeanConfiguration {
    @Bean
    public ServletRegistrationBean getServletRegistrationBean () {
        //绑定Servlet
        ServletRegistrationBean bean = new ServletRegistrationBean(new PersonController());
        //添加服务路径
        bean.addUrlMappings("/personTestUrl");
        return bean;
    }
    
    /**
     * 创建FeignClient
     */
    @Bean
    @ConditionalOnMissingBean
    public Client feignClient(CachingSpringLoadBalancerFactory cachingFactory,
                              SpringClientFactory clientFactory) {
        return new LoadBalancerFeignClient(new Client.Default(null, null),
                cachingFactory, clientFactory);
    }
}

客户端动态创建FeignClient通过服务名调用服务
  • 首先自定义接口 注意: 动态创建的FeignClient 不用加注解@FeignClient(“SERVICE-ID”)
/**
 * @author: RenChengLong
 */
public interface PersonFeignClient {
    /**
     * 测试
     * @param map 请求的body
     */
    @RequestMapping(value = "/personTestUrl", method = RequestMethod.POST)
    void personTest(@RequestBody Map<String,String> map);
}

  • 其次 在调用方法中 加入此FeignClient
//导入SpringCloud默认的Feign配置
@Import(FeignClientsConfiguration.class)
public class PersonTest{

    //自定义的FeignClient
    PersonFeignClient personFeignClient;

    //Feign 原生构造器
    Feign.Builder builder;
        
    //创建构造器
    public PersonTest(Decoder decoder, Encoder encoder, Client client, Contract contract) {
        this.builder = Feign.builder()
        					.client(client)
        					.encoder(encoder)
       						.decoder(decoder)
        					.contract(contract);
    }    

    public void test() {
        String serviceId="PERSON_TEST";
        Map<String, String> map = new HashMap<>();   
        map.put("parameter1","test1");
        //注意  构建的url  必须添加  http://   
        this.personFeignClient = this.builder.target(PersonFeignClient.class, "http://" + serviceId);
        
        //使用FeignClient请求服务
         this.personFeignClient.personTest(map);
    }

}

至此,SpringCloud通过服务名动态创建FeignClient已经完成

你可能感兴趣的:(SpringCloud,Feign,Servlet)