zoukankan      html  css  js  c++  java
  • Canal实现Redis缓存实时更新(二)

    在上一篇中介绍了Canal的安装和简单配置,本篇介绍与SpringBoot配合实现Redis缓存实时更新

    @CanalEventListener
    public class CanalDataEventListener {
        //SpringCloud组件,若不使用则替换为Service/Controller即可
        @Autowired
        private ContentFeign contentFeign;
        //Redis字符串
        @Autowired
        private StringRedisTemplate stringRedisTemplate;
    
        //自定义数据库的 操作来监听
        //destination = "example"
        @ListenPoint(destination = "example",
                schema = "changgou-content",
                table = {"tb_content", "tb_content_category"},
                eventType = {
                        CanalEntry.EventType.UPDATE,
                        CanalEntry.EventType.DELETE,
                        CanalEntry.EventType.INSERT})
        public void onEventCustomUpdate(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
            System.out.println("Action detected!");
            //1.获取列名 为category_id的值
            String categoryId = getColumnValue(eventType, rowData);
            //2.调用feign 获取该分类下的所有的广告集合
            Result<List<Content>> categoryresut = contentFeign.findByCategory(Long.valueOf(categoryId));
            List<Content> data = categoryresut.getData();
            //3.使用redisTemplate存储到redis中
            stringRedisTemplate.boundValueOps("content_" + categoryId).set(JSON.toJSONString(data));
        }
    
        private String getColumnValue(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
            String categoryId = "";
            //判断 如果是删除  则获取beforlist
            if (eventType == CanalEntry.EventType.DELETE) {
                for (CanalEntry.Column column : rowData.getBeforeColumnsList()) {
                    if (column.getName().equalsIgnoreCase("category_id")) {
                        categoryId = column.getValue();
                        return categoryId;
                    }
                }
            } else {
                //判断 如果是添加 或者是更新 获取afterlist
                for (CanalEntry.Column column : rowData.getAfterColumnsList()) {
                    if (column.getName().equalsIgnoreCase("category_id")) {
                        categoryId = column.getValue();
                        return categoryId;
                    }
                }
            }
            return categoryId;
        }
    }
    
  • 相关阅读:
    树莓派3 之 启动 和 系统配置
    树莓派3 之 初次使用
    Python 资源大全中文版
    乔布斯:遗失的访谈
    CSS3j背景渐变,字体颜色渐变,以及兼容IE写法
    系统设计相关
    JSON格式要求
    VUE解决空格和空行报错的问题
    css3实现悬停波浪效果
    css3实现匀速无限滚动效果
  • 原文地址:https://www.cnblogs.com/neptuneU/p/13863959.html
Copyright © 2011-2022 走看看