微服务框架——SpringCloud(二)

1.Feign声明式服务调用(负载均衡+熔断器)

  a.概念:Feign是一个声明式的Web Service客户端,它的目的就是让Web Service调用更加简单。Feign整合了Ribbon和Hystrix。

  b.新建springboot项目,依赖选择 Eureka Discovery 、Web 以及 Feign

  c.pom文件关键依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

        ......

    </dependencies>

    ......

 

  d.application.yml文件

spring:
  application:
    name: eureka-client-feign
server:
  port: 8086

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8081/eureka/

 

  c.启动类添加注解 @EnableDiscoveryClient 和 @EnableFeignClients

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class EurekaClientFeignApplication {

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

}

 

  d.创建接口调用服务

@FeignClient(value = "EUREKA-CLIENT-PRODUCER",fallback = FeignFallBack.class)
public interface FeignService {

    @RequestMapping(value = "/printProducer")
    public String printProducer(@RequestParam("param") String param);

}

 

  c.创建熔断器实现接口

@Component
public class FeignFallBack implements FeignService {

    @Override
    public String printProducer(String param) {
        return "连接消费服务失败,请求参数:" + param;
    }
}

 

  d.具体使用

@RestController
public class CommonController {

    @Resource
    FeignService feignService;

    @RequestMapping(value = "/print")
    public String print(String param){
        return feignService.printProducer(param);
    }

}

 

posted @ 2019-02-27 14:36  晨M风  阅读(151)  评论(0编辑  收藏  举报