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;
        }
    }
    
  • 相关阅读:
    「CH2401」送礼物 解题报告
    IO流总结
    关于Servlet中GET和POST方法的总结
    关于Java-枚举的总结
    JVM原理
    Form表单中method="post/get'的区别
    基于Servlet+JSP+JavaBean开发模式的用户登录注册
    浅谈jsp和servlet的区别
    serialVersionUID作用
    oracle的oci和thin区别
  • 原文地址:https://www.cnblogs.com/neptuneU/p/13863959.html
Copyright © 2011-2022 走看看