springCloud(10):使用Feign实现声明式REST调用-构造多参数请求
请求多参数的URL
假设请求的URL包含多个参数,如:http://localhost:8086/user1?id=1&username=nihao
1.1、Feign接口
@FeignClient(name = "spring-ribbon-eureka-client2")
public interface UserFeignClient {
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public User findById(@PathVariable("id") Long id) throws Exception;
/**get方式,多参数请求方式一*/
@RequestMapping(value = "/find", method = RequestMethod.GET)
public User find1(@RequestParam("id") Long id, @RequestParam("username") String username) throws Exception;
/**get方式,多参数请求方式二*/
@RequestMapping(value = "/find", method = RequestMethod.GET)
public User find2(@RequestParam Map<String, Object> map) throws Exception;
/**post方式,多参数请求*/
@RequestMapping(value = "/find", method = RequestMethod.POST)
public User find3(@RequestBody User user) throws Exception;
}
1.2、使用
package com.example.demo.controller;
import com.example.demo.feign.UserFeignClient;
import com.example.demo.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* 用户controller
*
* @Author: 我爱大金子
* @Description: 用户controller
* @Date: Create in 11:07 2017/7/10
*/
@RestController
public class UserController {
@Autowired
private UserFeignClient userFeignClient;
@GetMapping("/user/{id}")
public User findById(@PathVariable Long id) throws Exception {
if (null == id) {
return null;
}
return this.userFeignClient.findById(id);
}
@GetMapping("/user1")
public User find1(User user) throws Exception {
System.out.println("get方式,多参数请求方式一 : " + user);
if (null == user || null == user.getId()) {
return null;
}
return this.userFeignClient.find1(user.getId(), user.getUsername());
}
@GetMapping("/user2")
public User find2(User user) throws Exception {
System.out.println("get方式,多参数请求方式二 : " + user);
if (null == user || null == user.getId()) {
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", user.getId());
return this.userFeignClient.find2(map);
}
@PostMapping("/user3")
public User find3(User user) throws Exception {
System.out.println("POST方式,多参数请求方式 : " + user);
if (null == user || null == user.getId()) {
return null;
}
return this.userFeignClient.find3(user);
}
}
转载于:https://blog.51cto.com/1754966750/1948455