声明式服务调用:Spring Cloud Feign
说明:此次任务主要是通过Spring Cloud Feign提供的声明式服务绑定功能来实现对该服务接口的调用。
创建一个Spring Boot基础工程,命名为feign-consumer,并在pom.xml中引入spring-cloud-starter-eureka和spring-cloud-starter-feign依赖。
<?xml version=”1.0” encoding=”UTF-8”?>
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.2.1.RELEASE
com.ml
feign-consumer
0.0.1-SNAPSHOT
feign-consumer
Demo project for Spring Boot
1.8
Finchley.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-eureka
1.3.4.RELEASE
org.springframework.cloud
spring-cloud-starter-openfeign
2.0.1.RELEASE
org.springframework.cloud
spring-cloud-dependencies
${ spring-cloud.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
创建应用主类FeignConsumerApplication,并通过@EnableFeignClients注解开启Spring Cloud Feign的支持功能。
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class FeignConsumerApplication {public static void main(String[] args) {
SpringApplication.run(FeignConsumerApplication.class, args);
}
}
定义HelloService接口,通过@FeignClient注解指定服务名来绑定服务,然后再使用Spring MVC的注解来绑定具体该服务提供的REST接口。
@FeignClient(“hello-server”)
public interface HelloService {@RequestMapping("/hello")
String hello();
}
创建一个ConsumerController来实现对Feign客户端的调用。在helloConsumer函数中调用这个绑定了hello-service服务接口的客户端来向该服务发起/hello接口的调用。
@RestController
public class ConsumerController {private final Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
HelloService helloService;
@RequestMapping(value = "/feign-consumer", method = RequestMethod.GET)
public String helloConsumer() {
logger.info("进来了");
return helloService.hello();
}
}
application.properties中需填写以下几行代码
spring.application.name=feign-consumer
server.port=9001
eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/ribbon.eureka.enabled=true
还没有评论,来说两句吧...