1.首先mysql数据库得开启binlog
(这里不演示如何开启binlog,只演示如何用Canal实现Mysql Redis数据同步)
2.导入canal依赖
top.javatool
canal-spring-boot-starter
1.2.1-RELEASE
3.application.yml配置设置连接
#canal配置信息 canal: destination: example server: 121.77.14.222:11111 #连接地址
4.在要监听的表的实体类上加上注解
package com.sks.product.entity;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Builder;
import lombok.Data;
import org.springframework.data.annotation.Id;
import javax.persistence.Column;
import java.io.Serializable;
import java.util.Date;
import static com.baomidou.mybatisplus.annotation.IdType.INPUT;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@TableName("sks_product_info")
public class ProductInfoEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@TableId()
private Long id;
@Column(name = "product_name")
private String productName;
@Column(name = "classify_id")
private Long classifyId;
private Integer state;
private Integer acura;
@Column(name = "view_image")
private String viewImage;
@Column(name = "default_spec_id")
private Long defaultSpecId;
}
5.复写 EntryHandler<需要监听实体类> 接口 得到三个方法 insert() update() delete()
package com.sks.product.canal;
import com.sks.commons.util.RedisUtil;
import com.sks.product.config.RedisConfig;
import com.sks.product.entity.ProductCarouselEntity;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;
@CanalTable("sks_product_carousel")
@Component
public class ProductCarouselHandle implements EntryHandler {
@Override
public void insert(ProductCarouselEntity productCarouselEntity) {
//这是我向Redis里面插入数据的方法(你们可以写自己的方法)
RedisUtil.hSetNotExist(RedisConfig.PRODUCT_CAROUSEL.getMsg(),productCarouselEntity.getId(),productCarouselEntity);
}
@Override
public void update(ProductCarouselEntity before, ProductCarouselEntity after) {
//这是我向Redis里面更新数据的方法(你们可以写自己的方法)
RedisUtil.hSetNotExist(RedisConfig.PRODUCT_CAROUSEL.getMsg(),after.getId(),after);
}
@Override
public void delete(ProductCarouselEntity productCarouselEntity) {
//这是我向Redis里面删除数据的方法(你们可以写自己的方法)
RedisUtil.hDel(RedisConfig.PRODUCT_CAROUSEL.getMsg(),productCarouselEntity.getId());
}
}
然后就可以实现Mysql Redis数据同步了



