SpringCloud Feign多参数传递及需要注意的问题

目录
  • Feign多参数传递及注意的问题
    • 在服务提供者cloud-shop-userservice中新增几个方法
    • 修改feign的UserService,新增对应的方法
    • 在feign的controller中调用方法
    • 重启修改过的服务,查看服务注册是否正常
    • 使用工具调用这几个方法进行测试
  • Feign如何接收多个参数
    • 1.API
    • 2.Feign
    • 3.controller

Feign多参数传递及注意的问题

这边沿用前面的Eureka,Feign,Service

在服务提供者cloud-shop-userservice中新增几个方法

/**
	 * 保存用户
	 * 2018年1月18日
	 */
	@PostMapping("/user")
	public String aveUser(@RequestBody User user) {
		logger.info("保存用户 :" +user.toString());
		return "Success";
	}

	/**
	 * 根据用户名和密码查询用户
	 * 2018年1月18日
	 */
	@GetMapping("/findUser")
	public User findUserByNameAndPassword(String name ,String password) {
		logger.info("name :"+name +"---password :" +password);
		User user= new User();
		user.setName(name);
		user.setPassword(password);
		return user;
	}

修改feign的UserService,新增对应的方法

package cn.sh.daniel.service;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import cn.sh.daniel.entity.User;

@FeignClient(value = "cloud-shop-userservice")
public interface UserService {

	@GetMapping("/user/{id}")
	public User findUserById(@PathVariable("id")Long id);

	@PostMapping("/user/user")
	public String aveUser(@RequestBody User user) ;

	@GetMapping("/user/findUser")
	public User findUserByNameAndPassword(String name ,String password);
}

在feign的controller中调用方法

	/**
	 * 保存用户
	 * 2018年1月18日
	 */
	@PostMapping("/user")
	public String aveUser(@RequestBody User user) {
		return userService.aveUser(user);
	}

	/**
	 * 根据用户名和密码查询用户
	 * 2018年1月18日
	 */
	@GetMapping("/findUser")
	public User findUserByNameAndPassword(String name ,String password) {
		return userService.findUserByNameAndPassword(name, password);
	}

重启修改过的服务,查看服务注册是否正常

在启动过程中可以发现Feign服务启动报错:

为什么会报错呢?

这个方法有两个参数,而Feign去映射的时候它不会去自动给你区分那个参数是哪个,会直接给你报错

解决方法:添加注解,自己去指定要映射的属性

重新启动Feign服务:

启动成功!!!!

使用工具调用这几个方法进行测试

成功调用两个方法!!!!

Feign如何接收多个参数

feigin多个参数POST情况下

method(String str1,String str2,String str3);
method2(String str1,@RequestParam Map<String, Object> map,String str3);

1.API

package com.hwasee.hsc.api.redis;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Map;
/**
 * @author limaojing
 * @date 2020-07-28
 */
public interface RedisMapAPI {
    //===============================Map===============================
    @PostMapping("/redis/map/get")
    String getMap(@RequestParam(value = "key") String key, @RequestParam(value = "item") String item);
    @PostMapping("/redis/map/getAll")
    Map<Object, Object> getAllMap(@RequestParam(value = "key") String key);
    @PostMapping("/redis/map/set")
    Boolean setMap(@RequestParam(value = "key") String key, @RequestParam Map<String, Object> map);
    @PostMapping("/redis/map/setMapAndTime")
    Boolean setMapAndTime(@RequestParam(value = "key") String key, @RequestParam Map<String, Object> map, @RequestParam(value = "time") Long time);
    @PostMapping("/redis/map/setMapItem")
    Boolean setMapItem(@RequestParam(value = "key") String key, @RequestParam(value = "item") String item, @RequestParam(value = "value") String value);
    @PostMapping("/redis/map/setMapItemAndTime")
    Boolean setMapItemAndTime(@RequestParam(value = "key") String key, @RequestParam(value = "item") String item, @RequestParam(value = "value") String value, @RequestParam(value = "time") Long time);
    @PostMapping("/redis/map/del")
    void delMap(@RequestParam(value = "key") String key, @RequestParam(value = "items") Object[] items);
    @PostMapping("/redis/map/hashKey")
    Boolean mhashKey(@RequestParam(value = "key") String key, @RequestParam(value = "item") String item);
    @PostMapping("/redis/map/incr")
    Double incrMap(@RequestParam(value = "key") String key, @RequestParam(value = "item") String item, @RequestParam(value = "delta") Double delta);
    @PostMapping("/redis/map/decr")
    Double decrMap(@RequestParam(value = "key") String key, @RequestParam(value = "item") String item, @RequestParam(value = "delta") Double delta);
}

2.Feign

package com.hwasee.hsc.feign.redis;
import com.hwasee.hsc.api.redis.RedisMapAPI;
import com.hwasee.hsc.constants.ServiceConstants;
import org.springframework.cloud.openfeign.FeignClient;
/**
 * @author limaopeng
 * @date 2020-11-25
 */
@FeignClient(name = ServiceConstants.Services.SERVICE_REDIS)
public interface RedisMapFeign extends RedisMapAPI {
}

3.controller

如果实现了API就不用添加,没有实现就要添加

package com.hwasee.hsc.redis.controller;
import com.hwasee.hsc.redis.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
 * @author limaojing
 * @date 2020-07-28
 */
@RestController
@RequestMapping("/redis")
public class RedisController {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RedisUtil.redisMap redisMap;
    @Autowired
    private RedisUtil.redisString redisString;
    @Autowired
    private RedisUtil.redisSet redisSet;
    @Autowired
    private RedisUtil.redisList redisList;
    //===============================Common===============================
    @PostMapping("/changeDatabase")
    public void changeDatabase(Integer index){
        redisUtil.changeDatabase(index);
    }
    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     * @return
     */
    @PostMapping("/expire")
    public Boolean expire(String key, Long time) {
        return redisUtil.expire(key, time);
    }
    /**
     * 根据key获取过期时间
     *
     * @param key 键,不能为空
     * @return 时间秒,返回0代表永久有效
     */
    @PostMapping("/getExpire")
    public Long getExpire(String key) {
        return redisUtil.getExpire(key);
    }
    /**
     * 判断key是否存在
     *
     * @param key 键
     * @return 存在返回true,不存在返回false
     */
    @PostMapping("/hasKey")
    public Boolean hasKey(String key) {
        return redisUtil.hasKey(key);
    }
    /**
     * 删除缓存
     *
     * @param keys 可以传一个值,或多个值
     */
    @SuppressWarnings("unchecked")
    @PostMapping("/del")
    public void del(@RequestParam String[] keys) {
        redisUtil.del(keys);
    }
    //===============================String===============================
    /**
     * 获取缓存
     *
     * @param key 键
     * @return 值
     */
    @PostMapping("/string/get")
    public String getString(String key) {
        return redisString.get(key).toString();
    }
    /**
     * 缓存存入
     *
     * @param key   键
     * @param value 值
     * @return 操作成功返回true,失败返回false
     */
    @PostMapping("/string/set")
    public Boolean setString(String key, String value) {
        return redisString.set(key, value);
    }
    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return 操作成功返回true,失败返回false
     */
    @PostMapping("/string/setValueAndTime")
    public Boolean setValueAndTime(String key, String value, Long time) {
        return redisString.set(key, value, time);
    }
    /**
     * 递增
     *
     * @param key   键
     * @param delta 要增加的值
     * @return
     */
    @PostMapping("/string/incr")
    public Long incrString(String key, Long delta) {
        return redisString.incr(key, delta);
    }
    /**
     * 递减
     *
     * @param key   键
     * @param delta 要减小的值
     * @return
     */
    @PostMapping("/string/decr")
    public Long decrString(String key, Long delta) {
        return redisString.decr(key, delta);
    }
    //===============================Map===============================
    /**
     * 取得对应键值
     *
     * @param key  键
     * @param item 项
     * @return 值
     */
    @PostMapping("/map/get")
    public String getMap(String key, String item) {
        return redisMap.get(key, item);
    }
    /**
     * 获取hashKey对应的所有键值
     *
     * @param key 键
     * @return map形式返回键值对
     */
    @PostMapping("/map/getAll")
    public Map<Object, Object> getAllMap(String key) {
        return redisMap.getAll(key);
    }
    /**
     * 顾名思义,当然是set值啦
     *
     * @param key 键
     * @param map 对应的多个键值
     * @return 操作成功返回true,失败返回false
     */
    @PostMapping("/map/set")
    public Boolean setMap(String key, @RequestParam Map<String, Object> map) {
        return redisMap.set(key, map);
    }
    /**
     * 加强版set,可设置时间
     *
     * @param key  键
     * @param map  对应的多个键值
     * @param time 缓存失效时间
     * @return 操作成功返回true,失败返回false
     */
    @PostMapping("/map/setMapAndTime")
    public Boolean setMapAndTime(@RequestParam String key,@RequestParam Map<String, Object> map,@RequestParam Long time) {
        return redisMap.set(key, map, time);
    }
    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @return 操作成功返回true,失败返回false
     */
    @PostMapping("/map/setMapItem")
    public Boolean setMapItem(String key, String item, String value) {
        return redisMap.set(key, item, value);
    }
    /**
     * 加强版set,可设置时间
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  缓存失效时间
     * @return 操作成功返回true,失败返回false
     */
    @PostMapping("/map/setMapItemAndTime")
    public Boolean setMapItemAndTime(String key, String item, String value, Long time) {
        return redisMap.set(key, item,value, time);
    }
    /**
     * 删除hash表中的值
     *
     * @param key   键,不能为空
     * @param items 项,不能为空,可以为多个
     */
    @PostMapping("/map/del")
    public void delMap(String key,@RequestParam Object[] items) {
        redisMap.del(key, items);
    }
    /**
     * 判断hash表中是否存在某值
     *
     * @param key  键,不能为空
     * @param item 项,不能为空
     * @return 存在返回true,不存在返回false
     */
    @PostMapping("/map/hashKey")
    public Boolean mhashKey(String key, String item) {
        return redisMap.hasKey(key, item);
    }
    /**
     * hash递增
     *
     * @param key
     * @param item
     * @param delta 要增加多少
     * @return
     */
    @PostMapping("/map/incr")
    public Double incrMap(String key, String item, Double delta) {
        return redisMap.incr(key, item, delta);
    }
    /**
     * hash递减
     *
     * @param key
     * @param item
     * @param delta 要减少多少
     * @return
     */
    @PostMapping("/map/decr")
    public Double decrMap(String key, String item, Double delta) {
        return redisMap.decr(key, item, delta);
    }
    //===============================Set===============================
    /**
     * 根据key获取Set中的所有值
     *
     * @param key
     * @return
     */
    @PostMapping("/set/get")
    public Set<Object> getSet(String key) {
        return redisSet.get(key);
    }
    /**
     * 将数据放入set缓存
     *
     * @param key
     * @param values
     * @return 成功个数
     */
    @PostMapping("/set/setValue")
    public Long setValue(String key,@RequestParam Object[] values) {
        return redisSet.set(key, values);
    }
    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key
     * @param value
     * @return 存在返回true,不存在返回false
     */
    @PostMapping("/set/hashKey")
    public Boolean hashKey(String key, String value) {
        return redisSet.hasKey(key, value);
    }
    /**
     * 将数据放入set缓存,可设置时间
     *
     * @param key
     * @param time
     * @param values
     * @return 成功个数
     */
    @PostMapping("/set/setValueAndTime")
    public Long setValueAndTime(String key, Long time,@RequestParam Object[] values) {
        return redisSet.set(key, time, values);
    }
    /**
     * 获取set缓存的长度
     *
     * @param key
     * @return
     */
    @PostMapping("/set/getSize")
    public Long getSize(String key) {
        return redisSet.getSize(key);
    }
    /**
     * 移除set中值为value的项
     *
     * @param key
     * @param values
     * @return 移除的个数
     */
    @PostMapping("/set/remove")
    public Long remove(String key,@RequestParam Object[] values) {
        return redisSet.remove(key, values);
    }
    //===============================List===============================
    /**
     * 获取list缓存的内容
     *
     * @param key
     * @param start
     * @param end   0到结束,-1代表所有值
     * @return
     */
    @PostMapping("/list/get")
    public List<Object> get(String key, Long start, Long end) {
        return redisList.get(key, start, end);
    }
    /**
     * 获取list缓存的长度
     *
     * @param key
     * @return
     */
    @PostMapping("/list/getSize")
    public Long getListSize(String key) {
        return redisList.getSize(key);
    }
    /**
     * 通过索引 获取list中的值
     *
     * @param key
     * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     * @return
     */
    @PostMapping("/list/getByIndex")
    public Object getByIndex(@RequestParam("key") String key, @RequestParam("index") Long index) {
        return redisList.getByIndex(key, index);
    }
    /**
     * 将list放入缓存
     *
     * @param key
     * @param value
     * @return
     */
    @PostMapping("/list/setValue")
    public Boolean setValue(String key, Object value) {
        return redisList.set(key, value);
    }
    /**
     * 将list放入缓存,可设置时间
     *
     * @param key
     * @param value
     * @param time
     * @return
     */
    @PostMapping("/list/setValueAndTime")
    public Boolean setValueAndTime(String key, Object value, Long time) {
        return redisList.set(key, value, time);
    }
    /**
     * 将list放入缓存
     *
     * @param key
     * @param value
     * @return
     */
    @PostMapping("/list/setList")
    public Boolean setList(String key, List<Object> value) {
        return redisList.set(key, value);
    }
    /**
     * 将list放入缓存,可设置时间
     *
     * @param key
     * @param value
     * @param time
     * @return
     */
    @PostMapping("/list/setListAndTime")
    public Boolean setListAndTime(String key, List<Object> value, Long time) {
        return redisList.set(key, value, time);
    }
    /**
     * 根据索引修改list中的某条数据
     *
     * @param key
     * @param index
     * @param value
     * @return
     */
    @PostMapping("/list/updateByIndex")
    public Boolean updateByIndex(String key, Long index, Object value) {
        return redisList.updateIndex(key, index, value);
    }
    /**
     * 删除list中值为value的项
     *
     * @param key   键
     * @param count 要移除的个数
     * @param value
     * @return 移除的个数
     */
    @PostMapping("/list/remove")
    public Long remove(String key, Long count, Object value) {
        return redisList.remove(key, count, value);
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • SpringCloud Feign参数问题及解决方法

    这篇文章主要介绍了SpringCloud Feign参数问题及解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 今天遇到使用Feign调用微服务,传递参数时遇到几个问题 1.无参数 以GET方式请求 服务提供者 @RequestMapping("/hello") public String Hello(){ return "hello,provider"; } 服务消费者 @GetMapping("

  • Spring Cloud如何使用Feign构造多参数的请求

    本节我们来探讨如何使用Feign构造多参数的请求.笔者以GET以及POST方法的请求为例进行讲解,其他方法(例如DELETE.PUT等)的请求原理相通,读者可自行研究. GET请求多参数的URL 假设我们请求的URL包含多个参数,例如http://microservice-provider-user/get?id=1&username=张三 ,要如何构造呢? 我们知道,Spring Cloud为Feign添加了Spring MVC的注解支持,那么我们不妨按照Spring MVC的写法尝试一下:

  • Spring Cloud中关于Feign的常见问题总结

    一.FeignClient接口,不能使用@GettingMapping 之类的组合注解 代码示例: @FeignClient("microservice-provider-user") public interface UserFeignClient { @RequestMapping(value = "/simple/{id}", method = RequestMethod.GET) public User findById(@PathVariable(&quo

  • SpringCloud 如何使用feign时的复杂参数传递

    Feign传参注意 最近在用SpringCloud尝试重构以前的项目,使用Feign客户端组件来调用微服务,经常出现参数传不过去变成null的问题,网上查了一下发现feign在参数上的使用还是有一定的限制的,主要是要注意: 1. 当参数比较复杂时,feign即使声明为get请求也会强行使用post请求 2. 不支持@GetMapping类似注解声明请求,需使用 @RequestMapping(value = "url",method = RequestMethod.GET) 3. 使用

  • SpringCloud Feign多参数传递及需要注意的问题

    目录 Feign多参数传递及注意的问题 在服务提供者cloud-shop-userservice中新增几个方法 修改feign的UserService,新增对应的方法 在feign的controller中调用方法 重启修改过的服务,查看服务注册是否正常 使用工具调用这几个方法进行测试 Feign如何接收多个参数 1.API 2.Feign 3.controller Feign多参数传递及注意的问题 这边沿用前面的Eureka,Feign,Service 在服务提供者cloud-shop-user

  • 详解springcloud Feign的Hystrix支持

    本文介绍了springcloud Feign的Hystrix支持,分享给大家,具体如下: 一.Feign client中加入Hystrix的fallback @FeignClient(name="springboot-h2", fallback=HystrixClientFallback.class) //在fallback属性中指定断路器的fallback public interface UserFeignClient { // @GetMapping("/user/{i

  • SpringCloud Feign转发请求头(防止session失效)的解决方案

    微服务开发中经常有这样的需求,公司自定义了通用的请求头,需要在微服务的调用链中转发,比如在请求头中加入了token,或者某个自定义的信息uniqueId,总之就是自定义的一个键值对的东东,A服务调用B服务,B服务调用C服务,这样通用的东西如何让他在一个调用链中不断地传递下去呢?以A服务为例: 方案1 最傻的办法,在程序中获取,调用B的时候再转发,怎么获取在Controller中国通过注解获取,或者通过request对象获取,这个不难,在请求B服务的时候,通过注解将值放进去即可:简代码如下: 获取

  • 浅谈SpringCloud feign的http请求组件优化方案

    1 描述 如果我们直接使用SpringCloud Feign进行服务间调用的时候,http组件使用的是JDK的HttpURLConnection,每次请求都会新建一个连接,没有使用线程池复用.具体的可以从源码进行分析 2 源码分析 我们在分析源码很难找到入口,不知道从何开始入手,我们在分析SpringCloud feign的时候可用在配置文件下面我讲一下个人的思路. 1 首先我点击@EnableFeignClients 看一下这个注解在哪个资源路径下 如下图所示: 2 找到服务启动加载的配置文件

  • SpringCloud Feign的使用简介

    简介 feign是声明式的web service客户端,它让微服务之间的调用变得更简单了,类似controller调用service.Spring Cloud集成了Ribbon和Eureka,可在使用Feign时提供负载均衡的http客户端. 在springcloud中不仅可以使用Ribbo进行负载均衡,也可以使用Feign.Feign是在Ribbon的基础上进行了一次改进,采用接口的方式实现负载均衡. 使用 导入依赖 <dependency> <groupId>org.sprin

  • 解决SpringCloud Feign传对象参数调用失败的问题

    SpringCloud Feign传对象参数调用失败 不支持GET请求方式 使用Apache HttpClient替换Feign原生httpclient @RequestBody接收json参数 bootstrap-local.yml feign: httpclient: enabled: true pom.xml <!-- 使用Apache HttpClient替换Feign原生httpclient --> <dependency> <groupId>com.netf

  • Java之Springcloud Feign组件详解

    一.Feign是什么? OpenFeign是Spring Cloud提供的一个声明式的伪Hltp客户端,它使得调用远程服务就像调用本地服务一样简单,只需要创建一个接口并添加一个注解即可,Nacos很好的兼容了OpenFeign,OpenFeign默认集成了Ribbon, 所以在Nacos下使用OpenFeign默认就实现了负载均衡的效果. 二.使用步骤 1.消费方导入依赖 ···c org.springframework.cloud spring-cloud-starter-openfeign

  • 记一次线上SpringCloud Feign请求服务超时异常排查问题

    由于近期线上单量暴涨,第三方反馈部分工单业务存在查询处理失败现象,经排查是当前系统通过FeignClient调用下游系统出现部分超时失败(异常代码贴在下方). Caused by: feign.RetryableException: Read timed out executing POST http://xxxx        at feign.FeignException.errorExecuting(FeignException.java:84) ~[feign-core-10.1.0.j

  • Springcloud feign传日期类型参数报错的解决方案

    目录 feign传日期类型参数报错 Date类型参数报错 LocalDate类型报错 feign传参问题及传输Date类型参数时差的坑 下面说说两种解决方案 feign传参时候使用@DateTimeFormat注解的坑 feign传日期类型参数报错 Date类型参数报错 在Spring cloud feign接口中传递Date类型参数时报错,报错信息. 场景: 客户端传递一个new Date()的参数,服务端接受的参数和客户端有时间差. 客户端打印格式化的new Date(): 2018-05-

随机推荐