问题描述
在微服务架构中,我们不可避免的要使用到Feign去请求其他接口,这时就会有一个问题,如果Feign请求的接口需要返回一个对象,这个对象是其他微服务中的class,但是本服务中没有,接收时一般就只能将另一个微服务中的class放进本服务中了,对于一般的微服务而言只是需要其中的几个参数而已,这样做并不是最好的方案,而且一般其他的微服务接口都是返回JSON数据格式,更加不利于转义成其他格式,这里,我给大家分享一种不错的解决方法:
如图这个生产者服务的对象类
import java.io.Serializable;
public class Product implements Serializable {
private int id;
private String name;
/**
* 价格,分为单位
*/
private int price;
/**
* 库存
*/
private int store;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getStore() {
return store;
}
public void setStore(int store) {
this.store = store;
}
public Product(String name, int price, int store) {
this.name = name;
this.price = price;
this.store = store;
}
public Product(int id, String name, int price, int store) {
this.id = id;
this.name = name;
this.price = price;
this.store = store;
}
public Product() {
}
}
这是返回类的接口信息,改Controller已经加上了@RestController
注解,作用是将接口返回值序列号成JSON字符串
@RestController
@RequestMapping("/api/v1/product")
public class ProductController {
@Autowired
private ProductService productService;
/**
* 获取商品详情
* @param id
* @return
*/
@RequestMapping("/find")
public Object find(@RequestParam("id") int id){
Product product = this.productService.findById(id);
return product;
}
}
因为该接口的返回值已经是JSON格式了,所以说我们可以使用String类型接收,这样更稳定,不会像使用Map之类的对象接收时容易出现转义报错的现象。接下来我推荐使用JsonNode对象来去将该JSON字符串转成JsonNode对象,这个对象的使用方法跟HashMap容器很像,而且还有更多的API,具体使用看下图:
这是Service层中的调用转换类型
@Service
public class ProductOrderServiceImpl implements ProductOrderService {
@Autowired
private RestTemplate restTemplate;
@Autowired
private ProductClient productClient;
public ProductOrder save(int userId, int productId) {
String reponse=this.productClient.findById(productId);
//这里调用了一个自己写的方法来进行转换
JsonNode jsonNode= Utils.str2JsonNode(reponse);
ProductOrder productOrder = new ProductOrder();
productOrder.setCreateTime(new Date());
productOrder.setUserId(userId);
productOrder.setTradeNo(UUID.randomUUID().toString());
productOrder.setProductName(jsonNode.get("name").toString());
productOrder.setPrice(Integer.parseInt(jsonNode.get("price").toString()));
return productOrder;
}
}
转换工具类
/**
* 工具类
*/
public class Utils {
private static final ObjectMapper OBJECT_MAPPER=new ObjectMapper();
/**
* 字符串转json
* @param str
* @return
*/
public static JsonNode str2JsonNode(String str){
try {
return OBJECT_MAPPER.readTree(str);
} catch (IOException e) {
return null;
}
}
}