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调用接口一模一样的去调用就可以了

    最后的效果:



  • 相关阅读:
    smartFoxClinet客户端官方中文Doc
    testTrycatch和catch中的应用程序恢复
    这几天做仿豆丁网flash文档阅读器,百度文库阅读器经验总结
    怎么通过生成动态对象名来调用一个对象?
    AS3的Number类型变量不指定初始值,则其初始值为NaN,而不是0.0
    最适合女生的五大紧缺游戏开发职位
    [阻塞和非阻塞]
    网络游戏客户端的日志输出
    我心目中的MMO
    和某游戏猎头的对话
  • 原文地址:https://www.cnblogs.com/tplovejava/p/10356908.html
Copyright © 2011-2022 走看看