spring cloud feign 服务调用
***********************
引入jar包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
***********************
相关注解
FeignClient
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FeignClient {
@AliasFor("name")
String value() default "";
@AliasFor("value")
String name() default "";
Class<?>[] configuration() default {};
Class<?> fallback() default void.class;
Class<?> fallbackFactory() default void.class;
String url() default "";
String path() default "";
String qualifier() default "";
String contextId() default "";
boolean decode404() default false;
boolean primary() default true;
}
***********************
服务提供端
*****************
配置文件
application.yml
spring:
cloud:
consul:
host: 172.18.0.20
port: 8500
application:
name: hello-provider
*****************
controller 层
HelloController
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
return "hello world";
}
@RequestMapping("/hello2")
public String hello(@RequestParam("name") String name){
System.out.println(name);
return "hello world2";
}
}
***********************
服务消费端
*****************
配置文件
application.yml
spring:
application:
name: feign-consumer
cloud:
consul:
host: 172.18.0.20
port: 8500
*****************
service 层
HelloService
@FeignClient(name = "hello-provider")
public interface HelloService {
@RequestMapping("/hello")
String hello();
@RequestMapping("/hello2")
String hello2(@RequestParam("name")String name);
}
*****************
controller 层
HelloController
@RestController
public class HelloController {
@Autowired
private HelloService helloService;
@RequestMapping("/get")
public String hello(){
return helloService.hello();
}
@RequestMapping("/get2")
public String hello2(@RequestParam("name")String name){
return helloService.hello2(name);
}
}
*****************
启动类
DemoApplication:加注解@EnableFeignClients
@EnableFeignClients
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}