微服务框架——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);
    }

}

 

转载于:https://www.cnblogs.com/vettel0329/p/10443554.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值