Spring Data Redis-存储日期时发出

时间:2018-11-12 17:28:00

标签: java spring-boot redis jedis spring-data-redis

我正在使用Spring Boot + Spring data Redis示例将Date保存到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;

2 个答案:

答案 0 :(得分:0)

我建议您改用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;

答案 1 :(得分:-1)

通过使用自定义序列化程序,可以解决此问题。引用@ {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;