SpringCloudFeign声名式服务调用

在springccloudFeign的实现下,我们只需要创建一个接口并用注解的方式配置它,即可完成对服务提供方的接口绑定。
创建工程,导入依赖

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>

在主启动类上加注解开启springCloudFeign支持功能

@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class FeignConsumerApplication {

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

}

定义一个service接口,通过@FeignClient注解来指定服务名来绑定服务,然后在使用mvc注解绑定具体提供服务的REST接口

@FeignClient("hello-service")
public interface HelloService {

    @RequestMapping("/hello")
    String hello();
}

在controller中注入helloService,调用hello方法

@RestController
public class ConsumerController {
    @Autowired
    HelloService helloService;
    @RequestMapping(value = "/feign-consumer",method = RequestMethod.GET)
    public String helloConsumer(){
        return helloService.hello();
    }
}

配置文件

spring.application.name=feign-consumer
server.port=9001

eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/
原创文章 41 获赞 11 访问量 1495

猜你喜欢

转载自blog.csdn.net/weixin_44038332/article/details/105204169
今日推荐