Spring Data Redis - 存储日期时出现问题

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"

实体class是:

@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();
}

型号class

@MyJsonFormat("dd.MM.yyyy") 
@JsonSerialize(using = CustomDateSerializer.class)
private Date createdDate;

我建议改用 LocalDateTime(或 LocalDate,如果您愿意)。然后,您可以使用

注释您的字段
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
private LocalDateTime createdAt;

使用杰克逊的 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;