声明式服务调用:Spring Cloud Feign

叁歲伎倆 2023-07-08 13:26 83阅读 0赞
  1. 说明:此次任务主要是通过Spring Cloud Feign提供的声明式服务绑定功能来实现对该服务接口的调用。
  1. 创建一个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



  2. 创建应用主类FeignConsumerApplication,并通过@EnableFeignClients注解开启Spring Cloud Feign的支持功能。

    @EnableFeignClients
    @EnableDiscoveryClient
    @SpringBootApplication
    public class FeignConsumerApplication {

    1. public static void main(String[] args) {
    2. SpringApplication.run(FeignConsumerApplication.class, args);
    3. }

    }

  3. 定义HelloService接口,通过@FeignClient注解指定服务名来绑定服务,然后再使用Spring MVC的注解来绑定具体该服务提供的REST接口。

    @FeignClient(“hello-server”)
    public interface HelloService {

    1. @RequestMapping("/hello")
    2. String hello();

    }

  4. 创建一个ConsumerController来实现对Feign客户端的调用。在helloConsumer函数中调用这个绑定了hello-service服务接口的客户端来向该服务发起/hello接口的调用。

    @RestController
    public class ConsumerController {

    1. private final Logger logger = LoggerFactory.getLogger(getClass());
    2. @Autowired
    3. HelloService helloService;
    4. @RequestMapping(value = "/feign-consumer", method = RequestMethod.GET)
    5. public String helloConsumer() {
    6. logger.info("进来了");
    7. return helloService.hello();
    8. }

    }

  5. application.properties中需填写以下几行代码

    spring.application.name=feign-consumer
    server.port=9001
    eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/

    ribbon.eureka.enabled=true

发表评论

表情:
评论列表 (有 0 条评论,83人围观)

还没有评论,来说两句吧...

相关阅读