此应用程序利用了 Redis 核心数据结构、JSON、时间序列、搜索和查询功能。播种的数据随后用于显示可搜索的交易概述,以及实时更新的个人理财管理概述和最大支出者更新。
在应用程序启动时,在 app/server.js
中,会安排一个 cron 定期创建随机的银行交易,并将这些交易播种到 Redis 中。
//cron job to trigger createBankTransaction() at regular intervals
cron.schedule('*/10 * * * * *', async () => {
const userName = process.env.REDIS_USERNAME;
createBankTransaction(userName);
//...
});
balanceAfter
值将在时间序列中记录,该时间序列的键为 balance_ts
,用于每次交易。bigspenders
中,与之关联的fromAccountName
成员会根据交易金额递增。请注意,此金额可以是正数或负数。let balance = 100000.0;
const BALANCE_TS = 'balance_ts';
const SORTED_SET_KEY = 'bigspenders';
export const createBankTransaction = async () => {
//to create random bank transaction
let vendorsList = source.source; //app/transactions/transaction_sources.js
const random = Math.floor(Math.random() * 9999999999);
const vendor = vendorsList[random % vendorsList.length]; //random vendor from the list
const amount = createTransactionAmount(vendor.fromAccountName, random);
const transaction = {
id: random * random,
fromAccount: Math.floor((random / 2) * 3).toString(),
fromAccountName: vendor.fromAccountName,
toAccount: '1580783161',
toAccountName: 'bob',
amount: amount,
description: vendor.description,
transactionDate: new Date(),
transactionType: vendor.type,
balanceAfter: balance,
};
//redis json feature
const bankTransaction = await bankTransactionRepository.save(transaction);
console.log('Created bankTransaction!');
// ...
};
const createTransactionAmount = (vendor, random) => {
let amount = createAmount(); //random amount
balance += amount;
balance = parseFloat(balance.toFixed(2));
//redis time series feature
redis.ts.add(BALANCE_TS, '*', balance, { DUPLICATE_POLICY: 'first' });
//redis sorted set as secondary index
redis.zIncrBy(SORTED_SET_KEY, amount * -1, vendor);
return amount;
};
使用 RedisInsight 查看示例 bankTransaction
数据视图
下载 RedisInsight 以查看您的 Redis 数据或在工作台中使用原始 Redis 命令。