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

最后的效果:



猜你喜欢

转载自www.cnblogs.com/tplovejava/p/10356908.html