• cube.js websocket 实时数据更新说明


    cube.js 是支持数据实时更新的(基于websocket+refreshkey),以下是参考使用

    环境准备

    • docker-compose 文件
    version: "3"
    services:
      postgres:
        image: postgres:12.1
        environment:
          - POSTGRES_PASSWORD=dalong
        ports:
          - 5432:5432

    db sql

    CREATE TABLE testapi (
        a text,
        b text
    );
    • cube app
      cube.js
     
    // Cube.js configuration options: https://cube.dev/docs/config
    module.exports = {
        orchestratorOptions: {
            queryCacheOptions: {
              refreshKeyRenewalThreshold: 4,
            }
        },
        processSubscriptionsInterval:1,
    };

    schema

    cube(`testapi`, {
        sql: `select * from public.testapi`,
        dimensions: {
          a: {
            type: `string`,
            sql: `a`,
          },
     
          b: {
            type: `string`,
            sql: `b`,
          },
        },
      });

    .enb

    CUBEJS_DB_HOST=localhost
    CUBEJS_DB_NAME=postgres
    CUBEJS_DB_USER=postgres
    CUBEJS_DB_PASS=dalong
    CUBEJS_WEB_SOCKETS=true
    CUBEJS_DEV_MODE=true
    CUBEJS_SCHEDULED_REFRESH_TIMER=false
    CUBEJS_DB_TYPE=postgres 
    CUBEJS_WEB_SOCKETS=true
    CUBEJS_API_SECRET=ecea204a8257dc3d52416f16c89b67ea7e9a15e668721ef16b9a4aa29a74b1935e6bbb3dac0250c9a5ca03f31db82f80c3818316f1cb8929391744a3ca799f32

    web 集成

    react app (可以通过create react app 创建)
    package.json

     
    {
      "name": "my-app",
      "version": "0.1.0",
      "private": true,
      "dependencies": {
        "@cubejs-client/react": "^0.27.0",
        "@cubejs-client/ws-transport": "^0.28.38",
        "@testing-library/jest-dom": "^5.11.4",
        "@testing-library/react": "^11.1.0",
        "@testing-library/user-event": "^12.1.10",
        "antd": "^4.15.3",
        "react": "^17.0.2",
        "react-dom": "^17.0.2",
        "react-scripts": "4.0.3",
      },
      "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test",
        "eject": "react-scripts eject"
      },
      "eslintConfig": {
        "extends": [
          "react-app",
          "react-app/jest"
        ]
      },
      "browserslist": {
        "production": [
          ">0.2%",
          "not dead",
          "not op_mini all"
        ],
        "development": [
          "last 1 chrome version",
          "last 1 firefox version",
          "last 1 safari version"
        ]
      }
    }
     

    App.js

    import './App.css';
    import MyDocument from './MyDocument'
    function App() {
      return (
        <div className="App">
             <MyDocument />
        </div>
      );
    }
     
    export default App;

    MyDocument组件

    import React from 'react';
    import { Table } from 'antd';
    import { useCubeQuery } from '@cubejs-client/react';
    import cubejs from '@cubejs-client/core';
    import WebSocketTransport from '@cubejs-client/ws-transport';
    import 'antd/dist/antd.css';
     
    const cubejsApi = cubejs({
      transport: new WebSocketTransport({
        authorization: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2MzI2Njc5NzcsImV4cCI6MTYzMjc1NDM3N30.ki5AokHM6cgRAK7XUaZbOk27PDzu0vPRImzM442eoM0",
        apiUrl: 'ws://localhost:4000/cubejs-api/v1',
      }),
    });
     
    function Demo() {
      const { resultSet, isLoading, error, progress } = useCubeQuery(
        {"dimensions":["testapi.a","testapi.b"]},{
        cubejsApi,
        subscribe: true,
        });
     
      if (isLoading) {
        return <div>{progress && progress.stage && progress.stage.stage || 'Loading...'}</div>;
      }
     
      if (error) {
        return <div>{error.toString()}</div>;
      }
     
      if (!resultSet) {
        return null;
      }
     
      function demoapp(item){
        return item["shortTitle"]
      }
     
      const dataSource = resultSet.tablePivot();
      const columns = resultSet.tableColumns().map((item)=>{
     
        let info = {
          ...item,
          // fixed:item.shortTitle=="count",
          title:`${item.shortTitle}||测试`,
          shortTitle:`${item.title}`
        }
        return info
      })
      console.log(columns)
    return <div >
        <Table columns={columns} dataSource={dataSource} scroll={{ x: 1000, y: 300 }} />;
        </div>
    }
     
    // Create Document Component
     
    export default Demo;
     
     

    参考效果

    可以通过写入db数据测试

    说明

    几个配置参数比较重要
    cube.js

     
     orchestratorOptions: {
            queryCacheOptions: {
              refreshKeyRenewalThreshold: 4, //  加速数据变动
            }
        },
        processSubscriptionsInterval:5, // 可以加速数据变动

    .env
    CUBEJS_WEB_SOCKETS=true 制定开启websocket(实际上默认已经开启了)
    react 客户端链接,需要使用WebSocketTransport 同时useCubeQuery需要开启制定·subscribe: true
    以上内容参考自官方文档,示例demo 我已经push github 了,可以参考

    参考资料

    https://cube.dev/docs/real-time-data-fetch
    https://github.com/rongfengliang/cubejs-websocket

  • 相关阅读:
    VC++学习(1):Windows程序内部运行原理
    VC++学习(9):定制应用程序外观
    VC++学习(7):对话框编程
    VC++学习(3):MFC框架程序剖析
    VC++学习(5):文本编程
    VC++学习(4):简单绘图
    DbgPrint/KdPrint输出格式控制
    常用的正则表达式
    使用geoserver+openLayers加载google地图
    retunValue与opener的用法
  • 原文地址:https://www.cnblogs.com/rongfengliang/p/15341020.html
Copyright © 2020-2023  润新知