zoukankan      html  css  js  c++  java
  • spring cloud之Feign的使用

    原始的调用客户端的方式是通过注入restTemplate的方式

    restTemplate.getForObject("http://CLIENT/hello", String.class)

    通过feign的方式

    配置消费者项目cloud-consume

    pom.xml

    依赖jar

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

    application.yml

    添加启动feign 可实现错误回调

    feign:
      hystrix:
        enabled: true

    启动应用类

    ClondConsumeApplication.java

    添加注解@EnableFeignClients

    HelloService.java接口

    package com.tp.soft.cloudconsume.service;
    
    import com.tp.soft.cloudconsume.service.impl.HelloServiceFallback;
    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.web.bind.annotation.GetMapping;
    
    @FeignClient(value = "CLIENT", fallback = HelloServiceFallback.class)
    public interface HelloService {
        @GetMapping("/hello")
        String hello();
    }

    其中CLIENT则为注册中心被调用的应用名,/hello完全和客户端业务接口一样,fallback则为错误回调的方法,同时可以防止应用雪崩效应.

    HelloServiceFallback.java接口

    package com.tp.soft.cloudconsume.service.impl;
    
    import com.tp.soft.cloudconsume.service.HelloService;
    import org.springframework.stereotype.Component;
    
    @Component
    public class HelloServiceFallback implements HelloService {
        @Override
        public String hello() {
    
            return "request error";
        }
    }

    HelloController.java

    package com.tp.soft.cloudconsume.controller;
    
    import com.tp.soft.cloudconsume.service.HelloService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.client.RestTemplate;
    
    import javax.annotation.Resource;
    
    @RestController
    public class HelloController {
    
    //    @Autowired
    //    RestTemplate restTemplate;
    
        @Resource
        private HelloService helloService;
    
        @GetMapping("hi")
        public String hi(){
            //return restTemplate.getForObject("http://CLIENT/hello", String.class);
            return helloService.hello();
        }
    }

    和原来在controller调用接口一模一样的去调用就可以了

    最后的效果:



  • 相关阅读:
    git 看不到别人创建的远程分支
    win10 系统开始菜单没反应的解决方法
    Fiddler 抓取 https 设置详解(图文)
    MongoDB + Express + art-template 项目实例-博客管理系统
    使用 XAML 格式化工具:XAML Styler
    [WPF] 在单元测试中使用 Prism 的 EventAggregator,订阅到 ThreadOption.UIThread 会报错
    分别使用 Python 和 Math.Net 调用优化算法
    在 Azure 上执行一些简单的 python 工作
    Linux默认路由与直连路由
    网站使用域名访问而禁止ip访问的配置
  • 原文地址:https://www.cnblogs.com/tplovejava/p/10356908.html
Copyright © 2011-2022 走看看