设为首页 加入收藏

TOP

spring cloud之Feign的使用
2019-09-17 16:48:55 】 浏览:27
Tags: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调用接口一模一样的去调用就可以了

 

最后的效果:

 

 

 

 



】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇spring cloud 初体验 下一篇零基础学Python--------入门篇 第..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目