人生得一知己足矣,斯世当以同怀视之。——鲁迅

今天在open-feign使用中踩坑,前两天介绍了feign使用url参数传参@SpringQueryMap使用

然后在进行时间类型的传输过程中发现默认的时间时区有误导致相差8小时,且格式不是我们规定的格式

首先我们需要配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Bean
public QueryMapEncoder queryMapEncoder() {
return new FieldQueryMapEncoder() {
@Override
public Map<String, Object> encode(Object object) throws EncodeException {
Map<String, Object> result = super.encode(object);
var map = (Map<Class<?>, Object>) ReflectUtil.getFieldValue(this, "classToMetadata");
var fields = (List<Field>) ReflectUtil.getFieldValue(map.get(object.getClass()), "objectFields");
var typeFieldsMap = Steam.of(fields).group(Field::getType);
Steam.of(typeFieldsMap.get(Date.class)).forEach((SerCons<Field>) dateField -> result.put(dateField.getName(), DateUtils.format((Date) dateField.get(object))));
Steam.of(typeFieldsMap.get(LocalDate.class)).forEach((SerCons<Field>) dateField -> result.put(dateField.getName(), DateUtils.format((LocalDate) dateField.get(object))));
Steam.of(typeFieldsMap.get(LocalDateTime.class)).forEach((SerCons<Field>) dateField -> result.put(dateField.getName(), DateUtils.format((LocalDateTime) dateField.get(object))));
return result;
}
};
}

这里是让其解析完毕后再用反射去实现,实际并不是最优解,主要是注入自己实现的QueryMapEncoder

然后日期序列化:全局日期请求转换处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.beans.PropertyEditorSupport;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

@Slf4j
@RestControllerAdvice
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) // 仅当为WebMvc应用时激活
public class GlobalUrlParamResolveHandler {

@InitBinder
public void initBinder(WebDataBinder binder) {
// Date 类型转换
binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
@Override
@SneakyThrows
public void setAsText(String text) {
setValue(DateUtils.textToDate(text));
}
});
// LocalDate类型转换
binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
setValue(DateUtils.textToLocalDate(text));
}
});
// LocalDateTime类型转换
binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
setValue(DateUtils.textToLocalDateTime(text));
}
});
}

}

成功解决!