[英]Spring Data Redis - Issue while storing Date
我正在使用Spring Boot + Spring data Redis
示例將日期保存到 Redis 緩存中。 雖然我使用了@DateTimeFormat @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
,但仍然發生持久性是長期價值。 看起來像是一毫秒。
有人可以指導我是否需要設置額外的配置來保持日期,如yyyy-MM-dd
。
HGETALL users:1
1) "_class"
2) "com.XXX.entity.User"
3) "userId"
4) "1"
5) "name"
6) "John"
7) "createdDate"
8) "1542043247352"
實體類:
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
@RedisHash("users")
public class User {
@Id
private Long userId;
private String name;
@DateTimeFormat
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private Date createdDate;
private List<Group> groups;
}
UPDATE-1 :: 根據我實施的建議,但仍然無法正常工作CustomDateSerializer.java
@Component
public class CustomDateSerializer extends JsonSerializer<Date> {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
@Override
public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
throws IOException, JsonProcessingException {
String formattedDate = dateFormat.format(date);
gen.writeString(formattedDate);
}
}
自定義界面
@Retention(RetentionPolicy.RUNTIME)
public @interface MyJsonFormat {
String value();
}
模型類
@MyJsonFormat("dd.MM.yyyy")
@JsonSerialize(using = CustomDateSerializer.class)
private Date createdDate;
我建議改用LocalDateTime
(或 LocalDate,如果您願意)。 然后,您可以使用
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
private LocalDateTime createdAt;
使用jackson的jsr310添加:
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
通過使用自定義序列化程序,可以解決這個問題。 參考 @ https://kodejava.org/how-to-format-localdate-object-using-jackson/#comment-2027
public class LocalDateSerializer extends StdSerializer<LocalDate> {
private static final long serialVersionUID = 1L;
public LocalDateSerializer() {
super(LocalDate.class);
}
@Override
public void serialize(LocalDate value, JsonGenerator generator, SerializerProvider provider) throws IOException {
generator.writeString(value.format(DateTimeFormatter.ISO_LOCAL_DATE));
}
}
POJO:
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate createdDate;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.