本文基于SpringCloud,使用的前提是客户端要与服务端注册到相同的eureka上,同时项目(SpringCloud)整合HttpServlet,通过HttpServlet自定义对外接口
org.springframework.cloud
spring-cloud-starter-openfeign
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();
}
}
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);
}
}
/**
* @author: RenChengLong
*/
public interface PersonFeignClient {
/**
* 测试
* @param map 请求的body
*/
@RequestMapping(value = "/personTestUrl", method = RequestMethod.POST)
void personTest(@RequestBody Map<String,String> map);
}
//导入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已经完成