具有可选参数请求的微服务通信



我有一个房间服务,它在请求时返回房间的详细信息http://localhost:8082/room/search/byRoomChar

@GetMapping(path = "/search/byRoomChar")
public @ResponseBody List<Room> byCapacity(@RequestParam(required = false) Integer capacity,
@RequestParam(required = false) Boolean isUnderMaintenance,
@RequestParam(required = false) String equipment) {
return roomRepository.findByRoomChar(capacity, isUnderMaintenance, equipment);
}

现在我想从预订服务请求这个@GetMapping,因为这是用户将使用http://localhost:8081/booking/search/byRoomChar.

@GetMapping(path = "/search/byRoomChar")
public @ResponseBody List<Room> byCapacity(@RequestParam(required = false) Integer capacity,
@RequestParam(required = false) Boolean isUnderMaintenance,
@RequestParam(required = false) String equipment) {
ResponseEntity<Room[]> roomsResponse = restTemplate.getForEntity("http://localhost:8082/room/search/byRoomChar?capacity=" + capacity + "&isUnderMaintenance=" +
isUnderMaintenance + "&equipment=" + equipment, Room[].class);
return Arrays.asList(roomsResponse.getBody());
}

房间实体代码:

package nl.tudelft.sem.template.entities;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "Room")
public class Room {
@EmbeddedId
private RoomId id;
@Column(name = "capacity")
private int capacity;
@Column(name = "numberOfPeople")
private int numberOfPeople;
@Column(name = "isUnderMaintenance", nullable = false)
private boolean isUnderMaintenance;
@Column(name = "equipment")
private String equipment;
public Room() {
}
public Room(long roomNumber, long buildingNumber, int capacity,
int numberOfPeople, boolean isUnderMaintenance, String equipment) {
RoomId id = new RoomId(roomNumber, buildingNumber);
this.id = id;
this.capacity = capacity;
this.numberOfPeople = numberOfPeople;
this.isUnderMaintenance = isUnderMaintenance;
this.equipment = equipment;
}
public RoomId getId() {
return id;
}
public void setId(RoomId id) {
this.id = id;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public int getNumberOfPeople() {
return numberOfPeople;
}
public void setNumberOfPeople(int numberOfPeople) {
this.numberOfPeople = numberOfPeople;
}
public boolean getIsUnderMaintenance() {
return isUnderMaintenance;
}
public void setUnderMaintenance(boolean underMaintenance) {
isUnderMaintenance = underMaintenance;
}
public String getEquipment() {
return equipment;
}
public void setEquipment(String equipment) {
this.equipment = equipment;
}
}

房间储存库代码:

package nl.tudelft.sem.template.repositories;
import java.util.List;
import nl.tudelft.sem.template.entities.Room;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface RoomRepository extends JpaRepository<Room, Integer> {
@Query("SELECT r FROM Room r WHERE (:number is null or r.id.number = :number)"
+ "and r.id.buildingNumber = :buildingNumber")
List<Room> findByRoomNum(@Param("number") Long number,
@Param("buildingNumber") Long buildingNumber);
@Query("SELECT r FROM Room r WHERE (:capacity is null or r.capacity = :capacity) and"
+ "(:isUnderMaintenance is null or r.isUnderMaintenance = :isUnderMaintenance) and"
+ "(:equipment is null or r.equipment = :equipment)")
List<Room> findByRoomChar(@Param("capacity") Integer capacity,
@Param("isUnderMaintenance") Boolean isUnderMaintenance,
@Param("equipment") String equipment);
}

然而,这并不起作用,因为当从预订服务调用getmapping时省略参数时,由于required=false,所有参数值都将变为null。这些信息在硬编码的url中被转换为字符串。

2021-12-04 17:13:03.883  WARN 16920 --- [nio-8082-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Boolean'; nested exception is java.lang.IllegalArgumentException: Invalid boolean value [null]]

如何使用代码中的可选参数发出gethttp请求?

UriComponentsBuilder可以帮助构造URI。它正确地处理可为null的查询参数。

String uri = UriComponentsBuilder.fromHttpUrl("http://localhost:8082/room/search/byRoomChar")
.queryParam("capacity", capacity)
.queryParam("isUnderMaintenance", isUnderMaintenance)
.queryParam("equipment", equipment)
.encode().toUriString();
ResponseEntity<Room[]> roomsResponse = restTemplate.getForEntity(uri, Room[].class);

此外,以下答案可能会有所帮助:https://stackoverflow.com/a/25434451/5990117

如果参数在您的Room API中不是强制性的,但您仍然在对数据库的调用中使用它们,如果它们实际上不是由用户提供的,那么您就有合理的默认值。大致如下(在这种情况下,您实际上不需要明确定义required = false(:

@GetMapping(path = "/search/byRoomChar")
public @ResponseBody List<Room> byCapacity(@RequestParam(defaultValue = "10") Integer capacity,
@RequestParam(defaultValue = "false") Boolean isUnderMaintenance,
@RequestParam(defaultValue = "default-equipment") String equipment) {
return roomRepository.findByRoomChar(capacity, isUnderMaintenance, equipment);
}

或者,您定义了一个没有额外参数的Repository方法,但这可能更棘手,因为您基本上需要null和非null参数的所有可能性。

这是因为当参数为null时构建的URI字符串如下所示:

http://localhost:8082/room/search/byRoomChar?isUnderMaintenance=null

由于";空";作为参数的值附加,文件室服务器尝试将其反序列化为其他类型时失败。例如,在您给出的错误消息中;isUnderMaintenance;应该是布尔值,但是是";空";一串

为了解决这个问题,我建议使用UriComponentBuilder

@Test
fun constructUriWithQueryParameter() {
val uri = UriComponentsBuilder.newInstance()
.scheme("http")
.host("localhost")
.port(8082)
.path("/room/search/byRoomChar")
.query("capacity={capa}")
.query("isUnderMaintenance={isUnderMaintenance}")
.query("equipment={equip}")
.buildAndExpand(null, null, null)
.toUriString()
assertEquals(
"http://localhost:8082/room/search/byRoomChar 
capacity=&isUnderMaintenance=&equipment=",
uri
)
}

我试着回答Petr Aleksandrov。看起来很干净,这很可能是最好的方法,但我得到了一个";不是绝对uri";例外

没有时间寻找答案,所以我创建了解决方法代码。一团糟,但它奏效了。

@GetMapping(path = "/search/byRoomChar")
public @ResponseBody List<Room> byCapacity(@RequestParam(required = false) Integer capacity,
@RequestParam(required = false) Boolean isUnderMaintenance,
@RequestParam(required = false) String equipment) {
if(capacity == null && isUnderMaintenance == null && equipment == null) {
ResponseEntity<Room[]> roomsResponse = restTemplate.getForEntity("http://localhost:8082/room/search/byRoomChar", Room[].class);
return Arrays.asList(roomsResponse.getBody());
}
String url = "http://localhost:8082/room/search/byRoomChar?";
if(capacity != null) {
url += "capacity=" + capacity + "&";
}
if(isUnderMaintenance != null) {
url += "isUnderMaintenance=" + isUnderMaintenance + "";
}
if(equipment != null) {
url += "equipment=" + equipment;
}
ResponseEntity<Room[]> roomsResponse = restTemplate.getForEntity(url, Room[].class);
return Arrays.asList(roomsResponse.getBody());
}

相关内容

  • 没有找到相关文章

最新更新