当前位置: 移动技术网 > IT编程>软件设计>架构 > spring cloud之Feign的使用

spring cloud之Feign的使用

2019年02月09日  | 移动技术网IT编程  | 我要评论
原始的调用客户端的方式是通过注入restTemplate的方式 通过feign的方式 配置消费者项目cloud-consume pom.xml 依赖jar application.yml 添加启动feign 可实现错误回调 启动应用类 ClondConsumeApplication.java 添加注 ...

原始的调用客户端的方式是通过注入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调用接口一模一样的去调用就可以了

 

最后的效果:

 

 

 

 



如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网