Spring-Cloud | openfeign使用细节

写在前面的话

各位,下午好!

我比较喜欢用 fegin 来实现微服务之间的调用,但是feign使用的那些细节,是get到了吗?本节我将使用Spring Boot 2.0.5.RELEASE + Spring Cloud SR1 + openfeign并结合实际的使用,教你使用feign的姿势。

项目架构

我们先对测试架构一番,看图

针对Feign的使用测试架构图

简单来说,就是服务模块化分为:model层、API层、service层,其他服务就可以依赖API层。

另外,我们看一下,Spring官网提供的一段关于Feign Inheritance Support代码:

Feign Inheritance Support

下面我们就动手写例子。

测试实例

1、先看一下完成后的目录截图

测试项目目录结构

我们看 apimodelservicefeign-use之间的依赖关系。
api依赖model
service依赖api,实现api接口
feign-use依赖api,client继承api,并注入spring bean

2、使用公益eureka,这样我们就省略构建服务注册中心了

eureka:
  client:
    service-url:
      defaultZone: http://eureka.fengwenyi.com/eureka/

3、关于项目多模块化,看这里:https://github.com/fengwenyi/multi-module

4、model中的代码:

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

/**
 * @author Wenyi Feng
 * @since 2018-09-15
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class User {

    /** 标识 */
    private String uuid;

    /** 姓名 */
    private String name;

    /** 年龄 */
    private Integer age;
}

5、API接口

import com.fengwenyi.data.model.User;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Wenyi Feng
 * @since 2018-09-15
 */
public interface API {

    /**
     * 获取users
     * @return
     */
    @GetMapping("/getUsers")
    List<User> getUsers();

    /**
     * 根据用户ID获取user
     * @param uuid 用户ID
     * @return
     */
    @GetMapping("/getUserById/{uuid}")
    User getUserById(@PathVariable("uuid") String uuid);

    /**
     * 添加用户
     * @param user 用户对象
     * @return
     */
    @PostMapping("/addUser")
    boolean addUser(@RequestBody User user);

    /**
     * 根据用户ID修改用户信息
     * @param uuid 用户ID
     * @param user
     * @return
     */
    @PostMapping("/updateUserById/{uuid}")
    boolean updateUserById(@PathVariable("uuid") String uuid, @RequestBody User user);

    /**
     * 根据用户ID修改用户信息
     * @param uuid 用户ID
     * @param age 用户年龄
     * @return
     */
    @PostMapping("/updateById/{uuid}")
    boolean updateUserAgeById(@PathVariable("uuid") String uuid, @RequestBody Integer age);

    /**
     * 根据用户ID删除用户
     * @param uuid 用户ID
     * @return
     */
    @DeleteMapping("/deleteUserById/{uuid}")
    boolean deleteUserById(@PathVariable("uuid") String uuid);
}

6、API实现

import com.fengwenyi.data.API;
import com.fengwenyi.data.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootApplication
@EnableDiscoveryClient
@RestController
@Slf4j
public class FeignAPIApplication implements API {

    public static void main(String[] args) {
        SpringApplication.run(FeignAPIApplication.class, args);

//        ApplicationContextAware
//        BeanUtils
    }

    Map<String, User> userMap = new HashMap<>();

    @Override
    public List<User> getUsers() {
        if (userMap == null || userMap.isEmpty())
            return null;
        List<User> userList = new ArrayList<>();
        for (String uuid : userMap.keySet()) {
            userList.add(userMap.get(uuid));
        }
        return userList;
    }

    @Override
    public User getUserById(@PathVariable String uuid) {
        if (userMap == null || userMap.isEmpty() || StringUtils.isEmpty(uuid))
            return null;
        return userMap.get(uuid);
    }

    @Override
    public boolean addUser(@RequestBody User user) {
        if (user == null)
            return false;

        String uuid = user.getUuid();

        if (uuid == null)
            return false;

        if (userMap.get(uuid) != null)
            return false;

        User lastUser = userMap.put(uuid, user);
        if (lastUser != null)
            log.warn("uuid对应的user已被替换,uuid={}, lastUser={}, user={}", uuid, lastUser, user);

        return true;
    }

    @Override
    public boolean updateUserById(@PathVariable String uuid, @RequestBody User user) {
        if (user == null || uuid == null)
            return false;

        if (userMap.get(uuid) == null)
            return false;

        User lastUser = userMap.put(uuid, user);
        if (lastUser != null)
            log.warn("uuid对应的user已被替换,uuid={}, lastUser={}, user={}", uuid, lastUser, user);

        return true;
    }

    @Override
    public boolean updateUserAgeById(@PathVariable String uuid, @RequestBody Integer age) {
        if (age == null || uuid == null || age < -1)
            return false;

        User user = userMap.get(uuid);
        if (user == null)
            return false;

        User lastUser = userMap.put(uuid, user.setAge(age));
        if (lastUser != null)
            log.warn("uuid对应的user已被替换,uuid={}, lastUser={}, user={}", uuid, lastUser, user);

        return true;
    }

    @Override
    public boolean deleteUserById(@PathVariable String uuid) {
        if (uuid == null)
            return false;

        if (userMap.get(uuid) == null)
            return false;

        User lastUser = userMap.remove(uuid);

        if (lastUser != null)
            log.warn("uuid对应的user已被删除,uuid={}, lastUser={}", uuid, lastUser);

        return true;
    }
}

7、API继承

import com.fengwenyi.data.API;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;

/**
 * @author Wenyi Feng
 * @since 2018-09-15
 */
@FeignClient("feignapi")
public interface APIClient extends API {
}

8、写调用测试代码

import com.fengwenyi.data.model.User;
import com.fengwenyi.javalib.util.StringUtil;
import com.fengwenyi.javalib.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@RestController
public class FeignUseApplication {

    public static void main(String[] args) {
        SpringApplication.run(FeignUseApplication.class, args);
    }

    @Autowired
    private APIClient apiClient;


    @GetMapping("/add/{name}/{age}")
    public Object add(@PathVariable("name") String name, @PathVariable("age") Integer age) {
        if (StringUtil.isEmpty(name)
                || age == null
                || age < 0)
            return false;
        return apiClient.addUser(new User()
                .setUuid(Utils.getUUID())
                .setName("张三")
                .setAge(20));
    }

    @GetMapping("/updateUser/{uuid}")
    public Object updateUser(@PathVariable("uuid") String uuid) {
        if (StringUtil.isEmpty(uuid))
            return false;
        User user = apiClient.getUserById(uuid);
        if (user == null)
            return false;
        return apiClient.updateUserById(uuid,
                user.setName("张三 - Zhangsan")
                        .setAge(21));
    }

    @GetMapping("/update/{uuid}")
    public Object update(@PathVariable("uuid") String uuid) {
        if (StringUtil.isEmpty(uuid))
            return false;
        User user = apiClient.getUserById(uuid);
        if (user == null)
            return false;
        return apiClient.updateUserAgeById(uuid, 23);
    }

    @GetMapping("/delete/{uuid}")
    public Object delete(@PathVariable("uuid") String uuid) {
        if (StringUtil.isEmpty(uuid))
            return false;
        User user = apiClient.getUserById(uuid);
        if (user == null)
            return false;
        return apiClient.deleteUserById(uuid);
    }

    @GetMapping("gets")
    public Object gets() {
        return apiClient.getUsers();
    }

    @GetMapping("/get/{uuid}")
    public Object get(@PathVariable("uuid") String uuid) {
        if (StringUtil.isEmpty(uuid))
            return null;
        return apiClient.getUserById(uuid);
    }
}

关于测试

使用测试工具测试API

1、添加操作

http://localhost:8080/add/张三/19
http://localhost:8080/add/李四/18
http://localhost:8080/add/王五/17

2、查询

我们通过这个接口,看一下添加的情况:

http://localhost:8080/gets

响应
不好意思,上面代码有点问题。修改了下。

[
    {
        "uuid":"fddde49a35fe4947950571a93ebfaa1d",
        "name":"张三",
        "age":19
    },
    {
        "uuid":"e136860677a7463d8bcc3c88e0801931",
        "name":"王五",
        "age":17
    },
    {
        "uuid":"b440ebdf36964b62aea2025549409d4a",
        "name":"李四",
        "age":18
    }
]

单个查询

http://localhost:8080/get/e136860677a7463d8bcc3c88e0801931

响应

{
    "uuid":"e136860677a7463d8bcc3c88e0801931",
    "name":"王五",
    "age":17
}

3、修改操作

http://localhost:8080/updateUser/e136860677a7463d8bcc3c88e0801931

修改之后,数据是这样子的

[
    {
        "uuid":"fddde49a35fe4947950571a93ebfaa1d",
        "name":"张三",
        "age":19
    },
    {
        "uuid":"e136860677a7463d8bcc3c88e0801931",
        "name":"张三 - Zhangsan",
        "age":21
    },
    {
        "uuid":"b440ebdf36964b62aea2025549409d4a",
        "name":"李四",
        "age":18
    }
]

4、删除

http://localhost:8080/delete/b440ebdf36964b62aea2025549409d4a

删除之后,数据是这样子的

[
    {
        "uuid":"fddde49a35fe4947950571a93ebfaa1d",
        "name":"张三",
        "age":19
    },
    {
        "uuid":"e136860677a7463d8bcc3c88e0801931",
        "name":"张三 - Zhangsan",
        "age":21
    }
]

5、看一下控制台

控制台打印日志(部分截图)
2018-09-15 13:54:34.304  WARN 9732 --- [qtp489047267-34] c.fengwenyi.service.FeignAPIApplication  : 
uuid对应的user已被替换,uuid=e136860677a7463d8bcc3c88e0801931, 
lastUser=User(uuid=e136860677a7463d8bcc3c88e0801931, name=王五, age=17), 
user=User(uuid=e136860677a7463d8bcc3c88e0801931, name=张三 - Zhangsan, age=21)

2018-09-15 13:56:18.367  WARN 9732 --- [qtp489047267-35] c.fengwenyi.service.FeignAPIApplication  : 
uuid对应的user已被删除,uuid=b440ebdf36964b62aea2025549409d4a, 
lastUser=User(uuid=b440ebdf36964b62aea2025549409d4a, name=李四, age=18)
警告提醒

测试代码

点击这里,查看本节测试代码。

大抵就是这样子,感谢。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,284评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,115评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,614评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,671评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,699评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,562评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,309评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,223评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,668评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,859评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,981评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,705评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,310评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,904评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,023评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,146评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,933评论 2 355

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,657评论 18 139
  •  通过前面两章对Spring Cloud Ribbon和Spring Cloud Hystrix的介绍,我们已经掌...
    Chandler_珏瑜阅读 213,079评论 15 140
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,811评论 6 342
  • 软件是有生命的,你做出来的架构决定了这个软件它这一生是坎坷还是幸福。 本文不是讲解如何使用Spring Cloud...
    Bobby0322阅读 22,651评论 3 166
  • 第十九章:麒麟阁主 昆仑山上,凌楚将小青自画室带回青苑就发现了小青的异样之处:小青虽记起来千年前的故事却忘记了千年...
    大脚桶桶阅读 590评论 0 1