SpringCloud--openfeign
0 注意
消费者只能用@RequestMapping("/paramsUser")
注解
1 生产者
生产者暴露接口,返回值建议先转换为json
格式,然后再返回个服务的消费者,返回值类型为Object
类型。
1 生产者操作
@RestController
@RequestMapping("/img")
public class ImgController {
@PostMapping("/upload")
Object upload(String message ) {
// 接收消费者传来的json格式参数,然后转换为对应的类型
UmsUser umsUser = JSONObject.parseObject(message, UmsUser.class);
// 生产者对参数进行操作后,返回json格式的结果
String result = JSONObject.toJSONString(umsUser);
return result;
}
}
2 消费者操作
1 导包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
2 注解
1 主程序入口加注解
@EnableFeignClients
2 调用接口加注解(user
是生产者服务在服务中心注册的服务名)
@FeignClient("user")
3 消费者接口(建议使用第0种方式传递
)
0 消费者方法传参(建议使用json对象格式
来传递数据)
1.服务消费者(用@RequestParam
标记形参 ,paramsJson
传入前要被转换为json格式)
@RequestMapping("/paramsJson")
String paramsJson(@RequestParam String paramsJson);
1.服务提供者
@RequestMapping("/paramsJson")
public Object paramsJson( String paramsJson){
User u= JSONObject.parseObject(paramsJson,User.class);
return new User(u.getName()+"---服务提供者",u.getAge());
}
1 消费者方法传参(多个参数修正)
1.如果消费者使用多个形参传递,形参的名字要和服务提供者接收的形参名一致且要加@RequestParam
注解,不一致的话要用@RequestParam()
修正如:
getName( @RequestParam("name") String uname)
2 消费者方法传参(传递对象)
1.消费者正常传递
@RequestMapping("/paramsUser")
String paramsUser(User user);
2.接收者要用@RequestBody
来标记接收的对象
public Object paramsUser(@RequestBody User user){
return new User(user.getName()+"---服务提供者",user.getAge());
}
3 openfeign
传递文件
1 传递文件要在 @RequestMapping
中加额外的注解
注解1
导包导的是import org.springframework.http.MediaType;
consumes = MediaType.MULTIPART_FORM_DATA_VALUE
注解2
(@RequestPart("file")
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
@FeignClient("user")
public interface ImgService {
@RequestMapping(
value = "/img/upload",
method = RequestMethod.POST,
consumes = MediaType.MULTIPART_FORM_DATA_VALUE
)
String upload(@RequestPart("file") MultipartFile file);
}```