服务端不变,客户端在pom文件加入以下两个依赖:
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-jaxrs</artifactId>
<version>9.5.0</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1.1</version>
</dependency>
public interface RsClient {
@GET
@Path("/hello")
public String hello();
}
public class RsMain {
public static void main(String[] args) {
RsClient client=Feign.builder()
.contract(new JAXRSContract())
.target(RsClient.class,"http://localhost:8083/");
String result=client.hello();
System.out.println(result);
}
}
下面自定义注解以及注解翻译器:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyUrl {
String url();
String method();
}
public interface ContractClient {
@MyUrl(url="/hello",method="GET")
public String hello();
}
public class MyContract extends BaseContract{
@Override
protected void processAnnotationOnClass(MethodMetadata data, Class<?> clz) {
// TODO Auto-generated method stub
}
@Override
protected void processAnnotationOnMethod(MethodMetadata data, Annotation annotation, Method method) {
if(MyUrl.class.isInstance(annotation)){
MyUrl myUrl=method.getAnnotation(MyUrl.class);
String url=myUrl.url();
String httpMethod=myUrl.method();
data.template().method(httpMethod);
data.template().append(url);
}
}
@Override
protected boolean processAnnotationsOnParameter(MethodMetadata data, Annotation[] annotations, int paramIndex) {
// TODO Auto-generated method stub
return false;
}
}
public class ContractMain {
public static void main(String[] args) {
ContractClient client=Feign.builder()
.contract(new MyContract())
.target(ContractClient.class,"http://localhost:8083");
String result=client.hello();
System.out.println(result);
}
}
请求拦截器:
public class MyInterceptor implements RequestInterceptor{
public void apply(RequestTemplate template) {
template.header("Content-Type", "application/json");
System.out.println("这是请求拦截器");
}
}
public class InterceptorMain {
public static void main(String[] args) {
HelloClient client=Feign.builder()
.requestInterceptor(new MyInterceptor())
.target(HelloClient.class,
"http://localhost:8083");
String result=client.hello();
System.out.println(result);
}
}