一、传输对象的方式
将对象从内存传输到磁盘进行保存,或者进行网络传输,有两种方式:
- 实现Serializable接口,直接传输对象
- 转成json字符串后,进行字符串传输
二、直接传输对象
implements Serializable
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("learning_lesson")
@ApiModel(value="LearningLesson对象", description="学生课程表")
public class LearningLesson implements Serializable {private static final long serialVersionUID = 1L;@ApiModelProperty(value = "主键")@TableId(value = "id", type = IdType.ASSIGN_ID)private Long id;@ApiModelProperty(value = "学员id")private Long userId;@ApiModelProperty(value = "课程id")private Long courseId;@ApiModelProperty(value = "课程状态,0-未学习,1-学习中,2-已学完,3-已失效")private LessonStatus status;@ApiModelProperty(value = "每周学习频率,例如每周学习6小节,则频率为6")private Integer weekFreq;@ApiModelProperty(value = "学习计划状态,0-没有计划,1-计划进行中")private PlanStatus planStatus;@ApiModelProperty(value = "已学习小节数量")private Integer learnedSections;@ApiModelProperty(value = "最近一次学习的小节id")private Long latestSectionId;@ApiModelProperty(value = "最近一次学习的时间")private LocalDateTime latestLearnTime;@ApiModelProperty(value = "创建时间")private LocalDateTime createTime;@ApiModelProperty(value = "过期时间")private LocalDateTime expireTime;@ApiModelProperty(value = "更新时间")private LocalDateTime updateTime;
}
举例Redis直接传输对象
单元测试
//使用RedisTemplate<String,Object>需要配置一个RedisTemplate<String,Object>@Autowiredprivate RedisTemplate<String,Object> redisTemplate;@Testpublic void Test1_Add(){User u = User.builder().id(1000).name("zhangsan").phone("15730000001").build();redisTemplate.opsForValue().set("user1", u);}@Testpublic void Test1_Get(){Object obj = redisTemplate.opsForValue().get("user1");// 这里不能把Object强转为User类 否则会java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.gzdemo.redisdemo.domain.UserUser user = JSONUtil.toBean(JSONUtil.toJsonStr(obj), User.class);System.out.println(user);}
如果不implements Serializable,会报错,除非RedisTemplate<String,Object>配置了各种序列化器。