md5值 作为map<string,time_t>键值

针对聊天系统中因网络不稳定导致的消息重复发送问题,通过MD5算法生成唯一标识符实现消息去重,确保服务器能准确处理并响应每条消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在后台 服务器处理客户端发过来的数据时,由于通信网络传输 较差,实际收到了客户端的数据并进行了处理,给出了回应,但客户端由于网络原因判断为该条消息未发送成功,而重发。则服务器程序必须做出去重。
观察 实际解析到的消息结构体 如下
typedef struct
{
    time_t m_c_time,
    string m_localid,
    string m_buddyid,
    string m_msg,
}msg_info;

time 对多个msg_info实际并不唯一,所以 要根据 time_t m_c_time,
string m_localid, string m_buddyid,这三个参数生成一个md5值作为唯一的map索引(因为要求快速响应速度)
所以 将生成的md5值转化为string,作为map的key

将 time_t作为时间标记,作为 map的value

具体代码如下

    static std::map<string,time_t> s_chat_indentity;
    string md5Index;
    char md5buf[33];
    bzero(md5buf,33);
    int nLen =0;
    for(int i =0;i< 16;i++)
    {
        nLen += sprintf(md5buf+nLen,"%x",0xff&(md5Str[i]));// no "%02x"
    }
//实际生成的md5值以16进制打印出来的字符串 包含有0,所以不能用 "%02x",补齐
    md5Index = md5buf;
    time_t curtime;
    time(&curtime);
    std::map<string,time_t>::iterator it = s_chat_identify.find(md5Index);
    if(it != s_chat_identify.end())
    {
        s_chat_identify[md5Index]= curtime;
        //更新 md5 对应记录的最后一次出现的时间
        return false;
    }

    if(s_chat_identify.size() >= MAX_MAP_COUNT)
    {
        for(map<string,time_t>::iterator it = s_chat_identify.begin();it!= s_chat_identify.end();)
        {
            if(curtime - it->second > MAX_TIME_DIF)
            {
                s_chat_identify.erase(it++);
//对map的时间值进行排序耗时太大,所以改 选择 找出 时间差超过限制的老记录删除之
//另外 map的迭代器删除和vector的顺序存储容器不一样
            }
            else
            {
                ++it;
            }
        }       
    }

    if(s_chat_identify.size() >= MAX_MAP_COUNT_LIMIT)
    {
        s_chat_identify.erase(s_chat_identify.begin());
        //超过map的最大限,则选择删除 最开始的
        PRINT_LOG(__FILE__,__LINE__,ERROR_LEVEL,-1,"random del first record, map size is too larger : %d", s_chat_identify.size());
    }
    s_chat_identify.insert(pair<string, time_t>(md5Index, curtime));
<template> <div v-show="active === flag" class="step-main"> <div class="step-content"> <el-form ref="baseForm" :model="baseFormCurr" :rules="rules" label-width="105px"> <el-row :gutter="10"> <el-col :lg="8" :md="12" :sm="24" :xl="8" :xs="24"> <el-form-item label="表名称" prop="tableName"> <el-input v-model="baseFormCurr.tableName" autocomplete="off"></el-input> </el-form-item> </el-col> <el-col :lg="8" :md="12" :sm="24" :xl="8" :xs="24"> <el-form-item label="表类型" prop="tableType"> <el-select v-model="baseFormCurr.tableType" :disabled="formState.tableType" placeholder="请选择" style="width: 100%" @change="tableTypeChange"> <el-option v-for="item in dictCurr.table_type" :key="item.dictValue" :label="item.dictName" :value="item.dictValue" ></el-option> </el-select> </el-form-item> </el-col> <el-col :lg="8" :md="12" :sm="24" :xl="8" :xs="24"> <el-form-item label="描述" prop="comments"> <el-input v-model="baseFormCurr.comments" autocomplete="off" maxlength="100" show-word-limit ></el-input> </el-form-item> </el-col> <el-col :lg="8" :md="12" :sm="24" :xl="8" :xs="24"> <el-form-item label="数据库类型" prop="jdbcType"> <el-select ref="jdbcType" v-model="baseFormCurr.jdbcType" :disabled="formState.jdbcType" placeholder="请选择" style="width: 100%" @change="jdbcTypeChange"> <el-option v-for="item in dictCurr.jdbc_type" :key="item.dictValue" :label="item.dictName" :value="item.dictValue" ></el-option> </el-select> </el-form-item> </el-col> <el-col :lg="8" :md="12" :sm="24" :xl="8" :xs="24"> <el-form-item label="备注" prop="remark"> <el-input v-model="baseFormCurr.remark" autocomplete="off" maxlength="120" show-word-limit ></el-input> </el-form-item> </el-col> </el-row> </el-form> <vab-query-form> <vab-query-form-left-panel> <el-button :disabled="!baseFormCurr.jdbcType" icon="el-icon-plus" type="primary" @click="columnHandleAdd"> 添加 </el-button> <el-button icon="el-icon-plus" type="primary" @click="dialogVisible = true"> 常用字段 </el-button> <el-button :disabled="!selectRows.length > 0" icon="el-icon-delete" type="danger" @click="columnHandleDelete" > 删除 </el-button> </vab-query-form-left-panel> </vab-query-form> <el-form ref="tableForm" :model="{'tableForm': tableFormCurr}"> <el-table :data="tableFormCurr" :element-loading-text="elementLoadingText" border @selection-change="setSelectRows" > <el-table-column show-overflow-tooltip type="selection"></el-table-column> <el-table-column align="center" label="拖动" show-overflow-tooltip width="60" > <template v-slot="scope"> <el-button circle class="move-btn" icon="el-icon-d-caret" ></el-button> </template> </el-table-column> <el-table-column label="字段名称" min-width="200" prop="fieldName" show-overflow-tooltip > <template v-slot="scope"> <el-form-item :prop="'tableForm.'+scope.$index+'.fieldName'" :rules="columnRules.fieldName" class="el-form-item-table" > <el-input v-model="scope.row.fieldName" :disabled="scope.row.disabled" style="width: 100%"/> </el-form-item> </template> </el-table-column> <el-table-column label="字段类型" min-width="180" prop="fieldType" show-overflow-tooltip > <template v-slot="scope"> <el-form-item :prop="'tableForm.'+scope.$index+'.fieldType'" :rules="columnRules.fieldType" class="el-form-item-table" > <el-select v-model="scope.row.fieldType" :disabled="scope.row.disabled" default-first-option="" filterable placeholder="请选择" style="width: 100%"> <el-option v-for="item in baseDictData.fieldList" :key="item" :label="item" :value="item" ></el-option> </el-select> </el-form-item> </template> </el-table-column> <el-table-column label="字段长度" min-width="140" prop="fieldLength" show-overflow-tooltip > <template v-slot="scope"> <el-form-item :prop="'tableForm.'+scope.$index+'.fieldLength'" class="el-form-item-table" > <el-input-number v-model="scope.row.fieldLength" :disabled="scope.row.disabled" :max="20000" :min="0" controls-position="right" style="width: 100%" ></el-input-number> </el-form-item> </template> </el-table-column> <el-table-column label="字段精度" min-width="140" prop="fieldPrecision" show-overflow-tooltip > <template v-slot="scope"> <el-form-item :prop="'tableForm.'+scope.$index+'.fieldComments'" class="el-form-item-table" > <el-input-number v-model="scope.row.fieldPrecision" :disabled="scope.row.disabled" :max="100" :min="0" controls-position="right" style="width: 100%" ></el-input-number> </el-form-item> </template> </el-table-column> <el-table-column label="字段描述" min-width="240" prop="fieldComments" show-overflow-tooltip > <template v-slot="scope"> <el-form-item :prop="'tableForm.'+scope.$index+'.fieldComments'" :rules="columnRules.fieldComments" class="el-form-item-table" > <el-input v-model="scope.row.fieldComments" :disabled="scope.row.disabled" maxlength="100" show-word-limit style="width: 100%"/> </el-form-item> </template> </el-table-column> <el-table-column label="主键" min-width="80" prop="izPk" show-overflow-tooltip > <template v-slot="scope"> <el-form-item :prop="'tableForm.'+scope.$index+'.izPk'" class="el-form-item-table" > <el-switch v-model="scope.row.izPk" :active-value="1" :disabled="scope.row.disabled" :inactive-value="0" @change="pKChange(scope.row)" > </el-switch> </el-form-item> </template> </el-table-column> <el-table-column label="非空" min-width="80" prop="izNotNull" show-overflow-tooltip > <template v-slot="scope"> <el-form-item :prop="'tableForm.'+scope.$index+'.izNotNull'" class="el-form-item-table" > <el-switch v-model="scope.row.izNotNull" :active-value="1" :disabled="scope.row.disabled || scope.row.izPk === 1" :inactive-value="0" > </el-switch> </el-form-item> </template> </el-table-column> </el-table> </el-form> </div> <step-footer ref="step-footer" :flag="flag" :info-data="{ obj: this, baseForm: baseFormCurr, tableForm: tableFormCurr }" :max-flag="maxFlag" :min-flag="minFlag" ></step-footer> <!-- 选择预制字段--> <el-dialog :before-close="handleClose" :visible.sync="dialogVisible" append-to-body title="选择常见字段" width="30%"> <div> <template v-for="item in BuiltInFields"> <el-checkbox v-model="BuiltInFieldsSelect" :label="item.fieldName" border style="margin: 5px" @change="changeBuiltInFieldsSelect"></el-checkbox> </template> </div> <span slot="footer" class="dialog-footer"> <el-button @click="dialogVisible = false">取 消</el-button> <el-button type="primary" @click="AddDefaultFields">确 定</el-button> </span> </el-dialog> </div> </template> <script> import {isCode, isNull} from "@/utils/validate"; import StepFooter from "./footer/StepFooter.vue" import {deepClone} from "@/utils/clone"; import Sortable from "sortablejs"; import {uuid} from "@/utils"; import {getFieldTypes, getJavaFieldTypesBySafety} from "@/api/generator/tableManagement"; import {isNotNull} from "@/utils/valiargs"; import { useGlobalStore } from '@/pinia/global'; let state = useGlobalStore(); export default { name: "TableDataStep", components: {Sortable, StepFooter}, props: { active: { type: Number, default: () => { return 1; }, }, minFlag: { type: Number, default: () => { return 1; }, }, maxFlag: { type: Number, default: () => { return 1; }, }, baseForm: { type: Object, default: () => { return {}; }, }, tableForm: { type: Array, default: () => { return []; }, }, dict: { type: Object, default: () => { return {}; }, }, baseDictData: { type: Object, default: () => { return { fieldList: [], JavaFieldMap: {}, }; }, } }, data() { const validateTableName = (rule, value, callback) => { if (isNull(value)) { callback(new Error("请输入表名")); } if (!isCode(value)) { callback(new Error("表名只能为字母、数字或下划线")); } else { callback(); } }; const validateName = (rule, value, callback) => { if (!isCode(value)) { callback(new Error("只能为字母、数字或下划线")); } else { callback(); } }; return { BuiltInFieldsSelect: [],//已选中的字段 BuiltInFields: [ { "encryptData": null, "fieldName": "id", "fieldType": "bigint", "fieldLength": 19, "fieldPrecision": 0, "fieldComments": "唯一主键", "izPk": 1, "izNotNull": 1, "izShowList": null, "izShowForm": null, "javaType": "String", "showType": null, "dictTypeCode": null, "sort": 0, "validateType": null, "queryType": null, "disabled": false }, { "encryptData": null, "fieldName": "org_ids", "fieldType": "varchar", "fieldLength": 500, "fieldPrecision": 0, "fieldComments": "父级主键集合", "izPk": 0, "izNotNull": 0, "izShowList": null, "izShowForm": null, "javaType": "String", "showType": null, "dictTypeCode": null, "sort": 1, "validateType": null, "queryType": null, "disabled": false }, { "encryptData": null, "fieldName": "tenant_id", "fieldType": "bigint", "fieldLength": 19, "fieldPrecision": 0, "fieldComments": "多租户ID", "izPk": 0, "izNotNull": 0, "izShowList": null, "izShowForm": null, "javaType": "String", "showType": null, "dictTypeCode": null, "sort": 8, "validateType": null, "queryType": null, "disabled": false }, { "encryptData": null, "fieldName": "create_by", "fieldType": "bigint", "fieldLength": 19, "fieldPrecision": 0, "fieldComments": "创建者", "izPk": 0, "izNotNull": 1, "izShowList": null, "izShowForm": null, "javaType": "String", "showType": null, "dictTypeCode": null, "sort": 10, "validateType": null, "queryType": null, "disabled": false }, { "encryptData": null, "fieldName": "create_time", "fieldType": "datetime", "fieldLength": 0, "fieldPrecision": 0, "fieldComments": "创建时间", "izPk": 0, "izNotNull": 1, "izShowList": null, "izShowForm": null, "javaType": "String", "showType": null, "dictTypeCode": null, "sort": 11, "validateType": null, "queryType": null, "disabled": false }, { "encryptData": null, "fieldName": "update_by", "fieldType": "bigint", "fieldLength": 19, "fieldPrecision": 0, "fieldComments": "修改人", "izPk": 0, "izNotNull": 1, "izShowList": null, "izShowForm": null, "javaType": "String", "showType": null, "dictTypeCode": null, "sort": 12, "validateType": null, "queryType": null, "disabled": false }, { "encryptData": null, "fieldName": "update_time", "fieldType": "datetime", "fieldLength": 0, "fieldPrecision": 0, "fieldComments": "修改时间", "izPk": 0, "izNotNull": 1, "izShowList": null, "izShowForm": null, "javaType": "String", "showType": null, "dictTypeCode": null, "sort": 13, "validateType": null, "queryType": null, "disabled": false }, { "fieldName": "delected", "sort": 8, "izPk": 0, "izNotNull": 1, "izShowList": 0, "izShowForm": 0, "queryType": "", "fieldType": "int", "fieldLength": 1, "fieldPrecision": 0, "fieldComments": "删除", "javaType": "", "validateType": "", "showType": "", "dictTypeCode": "", "disabled": false }, { "fieldName": "version", "sort": 8, "izPk": 0, "izNotNull": 1, "izShowList": 0, "izShowForm": 0, "queryType": "", "fieldType": "int", "fieldLength": 1, "fieldPrecision": 0, "fieldComments": "乐观锁", "javaType": "", "validateType": "", "showType": "", "dictTypeCode": "", "disabled": false } ], dialogVisible: false,//选址内置字段 // 标示 flag: 1, title: "数据库表设置", dictCurr: [], baseFormCurr: {}, tableFormCurr: [], formState: { jdbcType: false, tableType: false, }, rules: { tableName: [ {required: true, trigger: "blur", validator: validateTableName}, ], tableType: [ {required: true, trigger: "change", message: "请选择表类型"}, ], jdbcType: [ {required: true, trigger: "change", message: "请选择数据库类型"}, ], comments: [ {required: true, trigger: "blur", message: "请输入描述"}, ], }, treeName: "parent_id", // 新增字段模版 columnFormTemp: { id: "", sort: 0, izPk: 0, izNotNull: 0, izShowList: 0, izShowForm: 0, queryType: "", fieldName: "", fieldType: "", fieldLength: 0, fieldPrecision: 0, fieldComments: "", javaType: "", validateType: "", showType: "", dictTypeCode: "", disabled: false, }, columnRules: { fieldName: [ {required: true, message: "请选择字段名称", trigger: "blur"}, {required: true, trigger: "blur", validator: validateName}, ], fieldType: [ {required: true, message: "请选择字段类型", trigger: "change"}, ], fieldComments: [ {required: true, message: "请输入字段描述", trigger: "blur"}, ] }, layout: "total, sizes, prev, pager, next, jumper", selectRows: "", elementLoadingText: "正在加载...", }; }, created() { // 告诉父节点 自己的 flag 编号 this.$emit("inform-flag", this.flag, this.title); }, mounted() { // 拷贝 props this.baseFormCurr = deepClone(this.baseForm); this.tableFormCurr = deepClone(this.tableForm); this.dictCurr = deepClone(this.dict); // 数据库字段类型 // this.dictCurr.field_type = this.$getDictList(this.baseFormCurr.jdbcType + "_data_type"); // 改成自己项目的字典项获取方式 // this.dict = state.sysDict; // this.dictCurr.field_type = state.sysDict.table_type; let dataType = this.baseFormCurr.jdbcType + "_data_type"; // JavaScript 对象支持两种属性访问方式:1点符号:object.propertyName ,适用于静态属性名。 2方括号符号:object[propertyName] ,适用于动态属性名,propertyName 可以是一个变量或表达式。 this.dictCurr.field_type = state.sysDict[dataType]; // 表拖动 this.rowDrop(); // 初始化数据 this.doGetFieldData(); }, watch: { baseForm(newV, oldV) { this.baseFormCurr = deepClone(newV); }, tableForm(newV, oldV) { this.tableFormCurr = deepClone(newV); }, dict(newV, oldV) { this.dictCurr = deepClone(newV); // 数据库字段类型 // this.dictCurr.field_type = this.$getDictList(this.baseFormCurr.jdbcType + "_data_type"); // 改成自己项目的字典项获取方式 // this.dict = state.sysDict; // this.dictCurr.field_type = state.sysDict.table_type; let dataType = this.baseFormCurr.jdbcType + "_data_type"; // JavaScript 对象支持两种属性访问方式:1点符号:object.propertyName ,适用于静态属性名。 2方括号符号:object[propertyName] ,适用于动态属性名,propertyName 可以是一个变量或表达式。 this.dictCurr.field_type = state.sysDict[dataType]; }, }, methods: { handleClose() { this.dialogVisible = false }, changeBuiltInFieldsSelect(e) { this.BuiltInFieldsSelect = this.removeElementsFromArray(this.BuiltInFieldsSelect, this.tableFormCurr) }, removeElementsFromArray(A, B) { A = A.filter(a => { let isEqual = B.some(b => b.fieldName === a); if (isEqual) { this.$message.error(`已存在字段:${a}`) } return !isEqual; }); return A; }, //添加默认字段 AddDefaultFields(params) { console.log(this.BuiltInFieldsSelect) for (const param of this.BuiltInFieldsSelect) { this.AddDefaultFields2(param) } this.dialogVisible = false }, //方法2 AddDefaultFields2(title) { let temp = null for (const tempElement of this.BuiltInFields) { if (tempElement.fieldName == title) { temp = tempElement } } this.tableFormCurr.push(temp); }, // 数据库类型发生改动 jdbcTypeChange(newValue) { const _this = this; this.tableFormCurr.jdbcType = this.$refs.jdbcType.value; this.$baseConfirm("更换数据库类型将会清空当前已设字段,你确定要更换吗", null, () => { // 改为新 _this.tableFormCurr.jdbcType = newValue; // 加载字典 // _this.dictCurr.field_type = _this.$getDictList(_this.baseFormCurr.jdbcType + "_data_type"); // 改成自己项目的字典项获取方式 // this.dict = state.sysDict; // this.dictCurr.field_type = state.sysDict.table_type; let dataType = this.baseFormCurr.jdbcType + "_data_type"; // JavaScript 对象支持两种属性访问方式:1点符号:object.propertyName ,适用于静态属性名。 2方括号符号:object[propertyName] ,适用于动态属性名,propertyName 可以是一个变量或表达式。 this.dictCurr.field_type = state.sysDict[dataType]; // 清空已有字段数据 _this.tableFormCurr = []; // 初始化数据 this.doGetFieldData(); }); }, // 表类型发生改动 tableTypeChange(newValue) { if (newValue === '0') { // 删除 parent_id 字段 for (let i = this.tableFormCurr.length - 1; i >= 0; i--) { let item = this.tableFormCurr[i]; if (item.fieldName === this.treeName) { this.tableFormCurr.splice(i, 1); break; } } } else if (newValue === '1') { // 删除 parent_id 字段 for (let i = this.tableFormCurr.length - 1; i >= 0; i--) { let item = this.tableFormCurr[i]; if (item.fieldName === this.treeName) { this.tableFormCurr.splice(i, 1); break; } } // 增加 parent_id 字段 let tmp = deepClone(this.columnFormTemp); tmp.disabled = true; tmp.fieldName = this.treeName; tmp.fieldType = "bigint"; tmp.fieldLength = 20; tmp.fieldComments = "上级ID"; tmp.javaType = "Integer"; tmp.izNotNull = 1; this.columnHandleAdd(tmp); } }, // 主键改动 pKChange(el) { if (!isNull(el)) { // 如果主键选中 则默认选中不可为空 if (el.izPk === 1) { el.izNotNull = 1; } else { el.izNotNull = 0; } } }, // ============================== async doGetFieldData() { this.$emit("loading"); // 通知父级 锁定当前表 this.$emit("inform-data", { fieldList: await this.doGetFieldTypes(), JavaFieldMap: await this.doGetJavaFieldTypesBySafety(), }); this.$emit("unLoading"); }, // 获得 数据类型 async doGetFieldTypes() { // const { data } = await getFieldTypes(); // 改成自己项目的数据返回格式 const res = await getFieldTypes(); const data = res.result.opsliData.data; if (isNotNull(data)) { return data; } return null; }, // 获得 Java 类型 (安全兜底模式) async doGetJavaFieldTypesBySafety() { // const { data } = await getJavaFieldTypesBySafety(); // 改成自己项目的数据返回格式 const res = await getJavaFieldTypesBySafety(); const data = res.result.opsliData.data; if (isNotNull(data)) { return data; } return null; }, // 行添加 columnHandleAdd(params) { let temp; if (!isNull(params) && !(params instanceof MouseEvent)) { temp = params; } else { temp = deepClone(this.columnFormTemp); } temp.id = "temp_" + uuid() if (this.tableFormCurr == null || this.tableFormCurr.length === 0) { temp.sort = 0; } else { temp.sort = this.tableFormCurr.length; } this.tableFormCurr.push(temp); }, // 行删除 columnHandleDelete(row) { if (row.id) { this.$baseConfirm("你确定要删除当前字段吗", null, () => { for (let i = this.tableFormCurr.length - 1; i >= 0; i--) { let item = this.tableFormCurr[i]; if (item.id === row.id) { // 树装接口 不允许删除 parent_id 字段 if (this.tableFormCurr.tableType === '1') { if (item.fieldName !== this.treeName) { this.tableFormCurr.splice(i, 1); } } else { this.tableFormCurr.splice(i, 1); } break; } } }); } else if (this.selectRows.length > 0) { const ids = this.selectRows.map((item) => item.id); this.$baseConfirm("你确定要删除当前字段吗", null, () => { for (let i = this.tableFormCurr.length - 1; i >= 0; i--) { let item = this.tableFormCurr[i]; if (ids.indexOf(item.id) !== -1) { // 树装接口 不允许删除 parent_id 字段 if (this.tableFormCurr.tableType === '1') { if (item.fieldName !== this.treeName) { this.tableFormCurr.splice(i, 1); } } else { this.tableFormCurr.splice(i, 1); } } } }); } else { this.$baseMessage("未选中任何行", "error"); return false; } }, // 行选中 setSelectRows(val) { this.selectRows = val; }, //行拖拽 rowDrop() { const tbody = this.$refs["tableForm"].$el .querySelector(".el-table__body-wrapper tbody"); const _this = this Sortable.create(tbody, { // 只能纵向拖动 axis: "y", // 限制触发事件只能某个元素可以触发 handle: ".move-btn", // 如果设置成true,则被拖拽的元素在返回新位置时,会有一个动画效果。 revert: true, // 如果设置成true,则元素被拖动到页面边缘时,会自动滚动。 scroll: true, onEnd({oldIndex, newIndex}) { _this.tableFormCurr[oldIndex].sort = newIndex; // 如果是 从后往前 移动 则 当前项改为newIndex 而 原newIndex 往后的所有内容全部向后顺产移动 if (oldIndex > newIndex) { for (let i = oldIndex; i > newIndex; i--) { _this.tableFormCurr[i - 1].sort = i; } } // 如果是 从前往后 移动 则 当前项改为newIndex 而 原newIndex 往后的所有内容全部向前顺产移动 else { for (let i = oldIndex; i < newIndex; i++) { _this.tableFormCurr[i + 1].sort = i; } } } }) }, }, }; </script> 这段代码是一个vue文件, 代码语法的框架是element-ui, 版本是2.15.13。我的前端项目vue版本是3.4.21, 框架ant-design-vue版本是4.2.1。现在的问题是文件内容和项目框架语法不一样, 请帮我把整个文件的代码内容修改成适配我项目框架的语法(注意:我的前端项目vue版本是3.4.21, 框架ant-design-vue版本是4.2.1,必须生成对应版本的语法)。 不要删除里边已经注释的代码, 即使有相同的代码, 你也不要省略代码, 把所有内容全部输出来, 需要保持原有的布局样式而调整转换代码。如果这个文件引入的别的文件, 不用你关心别的文件, 你不要给我生成别的文件内容, 最后生成一个vue文件给我, 如果输出内容过长而被终止截断了,请接着输出剩余的部分。转换后要求代码不报错, 按钮方法和底部方法名称要对应起来, 转换过程中不要遗漏代码, 注意:如果之前代码有$baseConfirm, 给我替换成Modal.confirm , 并且引入import { message, Modal } from “ant-design-vue”; 如果之前代码有$baseMessage, 给我替换成message.success或message.warning或message.error。 你好好思考分析下我的需求,不是将把Element UI组件替换为Ant Design Vue组件,你考虑转换后的版本了吗,不同版本语法api不一样,否则转换后的代码根本不能用。不要给我进行简化处理,方法内容不要给我留空,不要等着我补充,你都给我转换处理好。
最新发布
08-06
**谷粒随享** ## 第7章 专辑/声音详情 **学习目标:** - 专辑详情业务需求 - 专辑服务 1.专辑信息 2.分类信息 3.统计信息 4,主播信息 - 搜索服务:汇总专辑详情数据 - 专辑包含**声音列表(付费标识动态展示)** - MongoDB文档型数据库应用 - 基于**MongoDB**存储用户对于声音**播放进度** - 基于Redis实现排行榜(将不同分类下包含各个维度热门专辑排行) # 1、专辑详情 ![详情-专辑详情和声音列表](assets/详情-专辑详情和声音列表.gif) 专辑详情页面渲染需要以下四项数据: - **albumInfo**:当前专辑信息 - **albumStatVo**:专辑统计信息 - **baseCategoryView**:专辑分类信息 - **announcer**:专辑主播信息 因此接下来,我们需要在**专辑微服务**、**用户微服务**中补充RestFul接口实现 并且 提供远程调用Feign API接口给**搜索微服务**来调用获取。 在专辑**搜索微服务**中编写控制器**汇总专辑详情**所需**数据**: 以下是详情需要获取到的数据集 1. 通过专辑Id 获取专辑数据{已存在} 2. 通过专辑Id 获取专辑统计信息**{不存在}** 3. 通过三级分类Id 获取到分类数据{已存在} 4. 通过用户Id 获取到主播信息{存在} ## 1.1 服务提供方提供接口 ### 1.1.1 根据专辑Id 获取专辑数据(已完成) ### 1.1.2 根据三级分类Id获取到分类信息(已完成) ### 1.1.3 根据用户Id 获取主播信息(已完成) ### 1.1.4 根据专辑Id 获取统计信息 > YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/67 **AlbumInfoApiController** 控制器 ```java /** * 根据专辑ID查询专辑统计信息 * * @param albumId * @return */ @Operation(summary = "根据专辑ID查询专辑统计信息") @GetMapping("/albumInfo/getAlbumStatVo/{albumId}") public Result<AlbumStatVo> getAlbumStatVo(@PathVariable Long albumId) { AlbumStatVo albumStatVo = albumInfoService.getAlbumStatVo(albumId); return Result.ok(albumStatVo); } ``` **AlbumInfoService**接口 ```java /** * 根据专辑ID查询专辑统计信息 * * @param albumId * @return */ AlbumStatVo getAlbumStatVo(Long albumId); ``` **AlbumInfoServiceImpl**实现类 ```java /** * 根据专辑ID查询专辑统计信息 * * @param albumId * @return */ @Override public AlbumStatVo getAlbumStatVo(Long albumId) { return albumInfoMapper.getAlbumStatVo(albumId); } ``` **albumInfoMapper.java** ```java /** * 根据专辑ID查询专辑统计信息 * * @param albumId * @return */ AlbumStatVo getAlbumStatVo(@Param("albumId") Long albumId); ``` **albumInfoMapper.xml** ```sql <!--据专辑ID查询专辑统计信息--> <select id="getAlbumStatVo" resultType="com.atguigu.tingshu.vo.album.AlbumStatVo"> select stat.album_id, max(if(stat.stat_type='0401', stat.stat_num, 0)) playStatNum, max(if(stat.stat_type='0402', stat.stat_num, 0)) subscribeStatNum, max(if(stat.stat_type='0403', stat.stat_num, 0)) buyStatNum, max(if(stat.stat_type='0404', stat.stat_num, 0)) commentStatNum from album_stat stat where stat.album_id = #{albumId} and stat.is_deleted = 0 group by stat.album_id </select> ``` `service-album-client`模块**AlbumFeignClient** 接口中添加 ```java /** * 根据专辑ID查询专辑统计信息 * * @param albumId * @return */ @GetMapping("/albumInfo/getAlbumStatVo/{albumId}") public Result<AlbumStatVo> getAlbumStatVo(@PathVariable Long albumId); ``` **AlbumDegradeFeignClient**熔断类: ```java @Override public Result<AlbumStatVo> getAlbumStatVo(Long albumId) { log.error("[专辑模块]提供远程调用方法getAlbumStatVo服务降级"); return null; } ``` ## 1.2 服务调用方汇总数据 回显时,后台需要提供将数据封装到map集合中; ```java result.put("albumInfo", albumInfo); 获取专辑信息 result.put("albumStatVo", albumStatVo); 获取专辑统计信息 result.put("baseCategoryView", baseCategoryView); 获取分类信息 result.put("announcer", userInfoVo); 获取主播信息 ``` > YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/69 在`service-search` 微服务**itemApiController** 控制器中添加 ```java package com.atguigu.tingshu.search.api; import com.atguigu.tingshu.common.result.Result; import com.atguigu.tingshu.search.service.ItemService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Map; @Tag(name = "专辑详情管理") @RestController @RequestMapping("api/search") @SuppressWarnings({"all"}) public class itemApiController { @Autowired private ItemService itemService; /** * 根据专辑ID查询专辑详情相关数据 * * @param albumId * @return */ @Operation(summary = "根据专辑ID查询专辑详情相关数据") @GetMapping("/albumInfo/{albumId}") public Result<Map<String, Object>> getItemInfo(@PathVariable Long albumId) { Map<String, Object> mapResult = itemService.getItemInfo(albumId); return Result.ok(mapResult); } } ``` 接口与实现 ```java package com.atguigu.tingshu.search.service; import java.util.Map; public interface ItemService { /** * 根据专辑ID查询专辑详情相关数据 * * @param albumId * @return */ Map<String, Object> getItemInfo(Long albumId); } ``` ```java package com.atguigu.tingshu.search.service.impl; import cn.hutool.core.lang.Assert; import com.atguigu.tingshu.album.AlbumFeignClient; import com.atguigu.tingshu.model.album.AlbumInfo; import com.atguigu.tingshu.model.album.BaseCategoryView; import com.atguigu.tingshu.search.service.ItemService; import com.atguigu.tingshu.user.client.UserFeignClient; import com.atguigu.tingshu.vo.album.AlbumStatVo; import com.atguigu.tingshu.vo.user.UserInfoVo; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadPoolExecutor; @Slf4j @Service @SuppressWarnings({"all"}) public class ItemServiceImpl implements ItemService { @Autowired private AlbumFeignClient albumFeignClient; @Autowired private UserFeignClient userFeignClient; @Autowired private ThreadPoolExecutor threadPoolExecutor; /** * 根据专辑ID查询专辑详情相关数据 * 1.albumInfo:当前专辑信息 * 2.albumStatVo:专辑统计信息 * 3.baseCategoryView:专辑分类信息 * 4.announcer:专辑主播信息 * * @param albumId * @return */ @Override public Map<String, Object> getItemInfo(Long albumId) { //1.创建响应结果Map对象 HashMap在多线程环境下并发读写线程不安全:导致key覆盖;导致死循环 //采用线程安全:ConcurrentHashMap Map<String, Object> mapResult = new ConcurrentHashMap<>(); //2.远程调用专辑服务获取专辑基本信息-封装albumInfo属性 CompletableFuture<AlbumInfo> albumInfoCompletableFuture = CompletableFuture.supplyAsync(() -> { AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(albumId).getData(); Assert.notNull(albumInfo, "专辑:{}不存在", albumId); mapResult.put("albumInfo", albumInfo); return albumInfo; }, threadPoolExecutor); //3.远程调用专辑服务获取专辑统计信息-封装albumStatVo属性 CompletableFuture<Void> albumStatCompletableFuture = CompletableFuture.runAsync(() -> { AlbumStatVo albumStatVo = albumFeignClient.getAlbumStatVo(albumId).getData(); Assert.notNull(albumStatVo, "专辑统计信息:{}不存在", albumId); mapResult.put("albumStatVo", albumStatVo); }, threadPoolExecutor); //4.远程调用专辑服务获取专辑分类信息-封装baseCategoryView属性 CompletableFuture<Void> baseCategoryViewCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> { BaseCategoryView categoryView = albumFeignClient.getCategoryView(albumInfo.getCategory3Id()).getData(); Assert.notNull(categoryView, "分类:{}不存在", albumInfo.getCategory3Id()); mapResult.put("baseCategoryView", categoryView); }, threadPoolExecutor); //5.远程调用用户服务获取主播信息-封装announcer属性 CompletableFuture<Void> announcerCompletableFuture = albumInfoCompletableFuture.thenAcceptAsync(albumInfo -> { UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(albumInfo.getUserId()).getData(); Assert.notNull(userInfoVo, "用户:{}不存在", albumInfo.getUserId()); mapResult.put("announcer", userInfoVo); }, threadPoolExecutor); //6.组合异步任务,阻塞等待所有异步任务执行完毕 CompletableFuture.allOf( albumInfoCompletableFuture, albumStatCompletableFuture, baseCategoryViewCompletableFuture, announcerCompletableFuture ).join(); return mapResult; } } ``` ## 1.3 获取专辑声音列表 查询时,评论数关键字属性:commentStatNum ![](assets/image-20231005140148572.png) 需求:根据专辑ID分页查询声音列表,返回当前页10条记录,对每条声音付费标识处理。**关键点:哪个声音需要展示付费标识。** **默认每个声音付费标识为:false** 判断专辑付费类型:0101-免费、**0102-vip免费、0103-付费** - 用户未登录 - 专辑类型不是免费,将除了免费可以试听声音外,将本页中其余声音付费标识设置:true - 用户登录(获取是否为VIP) - 不是VIP,或者VIP过期(除了免费以外声音全部设置为付费) - 是VIP,专辑类型为付费 需要进行处理 - 统一处理需要付费情况 - 获取用户购买情况(专辑购买,或者声音购买)得到每个声音购买状态 - 判断根据用户购买情况设置声音付费标识 ### 1.3.1 获取用户声音列表付费情况 > YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/87 `user_paid_album` 这张表记录了用户购买过的专辑 `user_paid_track` 这张表记录了用户购买过的声音 如果购买过,则在map 中存储数据 key=trackId value = 1 未购买value则返回0 例如: - 某专辑第一页,除了试听的声音(前五)从6-10个声音需要在用户微服务中判断5个声音是否购买过 - 用户翻到第二页,从11-20个声音同样需要判断用户购买情况 **UserInfoApiController** 控制器: ```java /** * 该接口提供给给专辑服务,展示声音列表动态判断付费标识 * 判断当前用户某一页中声音列表购买情况 * * @param userId 用户ID * @param albumId 专辑ID * @param needChackTrackIdList 待检查购买情况声音列表 * @return data:{声音ID:购买结果} 结果:1(已购)0(未购买) */ @Operation(summary = "判断当前用户某一页中声音列表购买情况") @PostMapping("/userInfo/userIsPaidTrack/{userId}/{albumId}") public Result<Map<Long, Integer>> userIsPaidTrack( @PathVariable Long userId, @PathVariable Long albumId, @RequestBody List<Long> needChackTrackIdList) { Map<Long, Integer> mapResult = userInfoService.userIsPaidTrack(userId, albumId, needChackTrackIdList); return Result.ok(mapResult); } ``` **UserInfoService接口**: ```java /** * 判断当前用户某一页中声音列表购买情况 * * @param userId 用户ID * @param albumId 专辑ID * @param needChackTrackIdList 待检查购买情况声音列表 * @return data:{声音ID:购买结果} 结果:1(已购)0(未购买) */ Map<Long, Integer> userIsPaidTrack(Long userId, Long albumId, List<Long> needChackTrackIdList); ``` **UserInfoServiceImpl实现类**: ```java @Autowired private UserPaidAlbumMapper userPaidAlbumMapper; @Autowired private UserPaidTrackMapper userPaidTrackMapper; /** * 判断当前用户某一页中声音列表购买情况 * * @param userId 用户ID * @param albumId 专辑ID * @param needChackTrackIdList 待检查购买情况声音列表 * @return data:{声音ID:购买结果} 结果:1(已购)0(未购买) */ @Override public Map<Long, Integer> userIsPaidTrack(Long userId, Long albumId, List<Long> needChackTrackIdList) { //1.根据用户ID+专辑ID查询已购专辑表 LambdaQueryWrapper<UserPaidAlbum> userPaidAlbumLambdaQueryWrapper = new LambdaQueryWrapper<>(); userPaidAlbumLambdaQueryWrapper.eq(UserPaidAlbum::getAlbumId, albumId); userPaidAlbumLambdaQueryWrapper.eq(UserPaidAlbum::getUserId, userId); Long count = userPaidAlbumMapper.selectCount(userPaidAlbumLambdaQueryWrapper); if (count > 0) { //1.1 存在专辑购买记录-用户购买过该专辑,将待检查声音列表购买情况设置为:1 Map<Long, Integer> mapResult = new HashMap<>(); for (Long trackId : needChackTrackIdList) { mapResult.put(trackId, 1); } return mapResult; } //2. 不存在专辑购买记录-根据用户ID+声音列表查询已购声音表 LambdaQueryWrapper<UserPaidTrack> userPaidTrackLambdaQueryWrapper = new LambdaQueryWrapper<>(); userPaidTrackLambdaQueryWrapper.eq(UserPaidTrack::getUserId, userId); userPaidTrackLambdaQueryWrapper.in(UserPaidTrack::getTrackId, needChackTrackIdList); //获取本页中已购买声音列表 List<UserPaidTrack> userPaidTrackList = userPaidTrackMapper.selectList(userPaidTrackLambdaQueryWrapper); //2.1 不存在声音购买记录-将待检查声音列表购买情况设置为:0 if (CollectionUtil.isEmpty(userPaidTrackList)) { Map<Long, Integer> mapResult = new HashMap<>(); for (Long trackId : needChackTrackIdList) { mapResult.put(trackId, 0); } return mapResult; } //2.2 存在声音购买记录-循环判断待检查声音ID找出哪些是已购,哪些是未购买 List<Long> userPaidTrackIdList = userPaidTrackList.stream().map(UserPaidTrack::getTrackId).collect(Collectors.toList()); Map<Long, Integer> mapResult = new HashMap<>(); for (Long needCheckTrackId : needChackTrackIdList) { //如果待检查声音ID包含在已购声音Id集合中(已购买) if (userPaidTrackIdList.contains(needCheckTrackId)) { mapResult.put(needCheckTrackId, 1); } else { //反之则未购买声音 mapResult.put(needCheckTrackId, 0); } } return mapResult; } ``` `service-user-client`模块中**UserFeignClient** 远程调用接口中添加: ```java /** * 该接口提供给给专辑服务,展示声音列表动态判断付费标识 * 判断当前用户某一页中声音列表购买情况 * * @param userId 用户ID * @param albumId 专辑ID * @param needChackTrackIdList 待检查购买情况声音列表 * @return data:{声音ID:购买结果} 结果:1(已购)0(未购买) */ @PostMapping("/userInfo/userIsPaidTrack/{userId}/{albumId}") public Result<Map<Long, Integer>> userIsPaidTrack( @PathVariable Long userId, @PathVariable Long albumId, @RequestBody List<Long> needChackTrackIdList); ``` **UserDegradeFeignClient熔断类**: ```java @Override public Result<Map<Long, Integer>> userIsPaidTrack(Long userId, Long albumId, List<Long> needChackTrackIdList) { log.error("[用户服务]提供远程调用方法userIsPaidTrack执行服务降级"); return null; } ``` ### 1.3.2 查询专辑声音列表 在`service-album` 微服务中添加控制器. 获取专辑声音列表时,我们将数据都统一封装到**AlbumTrackListVo**实体类中 > YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/89 **TrackInfoApiController控制器** ```java /** * 用于小程序端专辑页面展示分页声音列表,动态根据用户展示声音付费标识 * * @param albumId * @param page * @param limit * @return */ @GuiGuLogin(required = false) @Operation(summary = "用于小程序端专辑页面展示分页声音列表,动态根据用户展示声音付费标识") @GetMapping("/trackInfo/findAlbumTrackPage/{albumId}/{page}/{limit}") public Result<Page<AlbumTrackListVo>> getAlbumTrackPage(@PathVariable Long albumId, @PathVariable Integer page, @PathVariable Integer limit) { //1.获取用户ID Long userId = AuthContextHolder.getUserId(); //2.封装分页对象 Page<AlbumTrackListVo> pageInfo = new Page<>(page, limit); //3.调用业务层封装分页对象 pageInfo = trackInfoService.getAlbumTrackPage(pageInfo, albumId, userId); return Result.ok(pageInfo); } ``` **TrackInfoService接口:** ```java /** * 用于小程序端专辑页面展示分页声音列表,动态根据用户展示声音付费标识 * * @param pageInfo MP分页对象 * @param albumId 专辑ID * @param userId 用户ID * @return */ Page<AlbumTrackListVo> getAlbumTrackPage(Page<AlbumTrackListVo> pageInfo, Long albumId, Long userId); ``` **TrackInfoServiceImpl实现类:** - 根据专辑Id 获取到专辑列表, - 用户为空的时候,然后找出哪些是需要付费的声音并显示付费 isShowPaidMark=true 付费类型: 0101-免费 0102-vip付费 0103-付费 - ​ 用户不为空的时候 - 判断用户的类型 - vip 免费类型 - 如果不是vip 需要付费 - 如果是vip 但是已经过期了 也需要付费 - 需要付费 - 统一处理需要付费业务 ​ 获取到声音Id列表集合 与 用户购买声音Id集合进行比较 将用户购买的声音存储到map中,key=trackId value = 1或0; 1:表示购买过,0:表示没有购买过 如果声音列表不包含,则将显示为付费,否则判断用户是否购买过声音,没有购买过设置为付费 ```java @Autowired private UserFeignClient userFeignClient; /** * 分页获取专辑下声音列表,动态根据用户情况展示声音付费标识 * * @param userId 用户ID * @param albumId 专辑ID * @param pageInfo 分页对象 * @return */ @Override public Page<AlbumTrackListVo> getAlbumTrackPage(Long userId, Long albumId, Page<AlbumTrackListVo> pageInfo) { //1.根据专辑ID分页获取该专辑下包含声音列表(包含声音统计信息)-默认声音付费标识为false pageInfo = albumInfoMapper.getAlbumTrackPage(pageInfo, albumId); //2.TODO 动态判断当前页中每个声音付费标识 关键点:找出付费情况 //2.根据专辑ID查询专辑信息 AlbumInfo albumInfo = albumInfoMapper.selectById(albumId); Assert.notNull(albumInfo, "专辑:{}不存在", albumId); String payType = albumInfo.getPayType(); //3.处理用户未登录情况 if (userId == null) { //3.1 判断专辑付费类型:VIP免费(0102)或 付费(0103) 除了免费试听外声音都应该设置付费标识 if (SystemConstant.ALBUM_PAY_TYPE_VIPFREE.equals(payType) || SystemConstant.ALBUM_PAY_TYPE_REQUIRE.equals(payType)) { //3.2 获取本页中声音列表,过滤将声音序号大于免费试听集数声音付费标识设置为true pageInfo.getRecords() .stream() .filter(albumTrackVo -> albumTrackVo.getOrderNum() > albumInfo.getTracksForFree()) //过滤获取除免费试听以外声音 .collect(Collectors.toList()) .stream().forEach(albumTrackListVo -> { albumTrackListVo.setIsShowPaidMark(true); }); } } else { //4.处理用户已登录情况 //4.1 远程调用用户服务获取用户信息得到用户身份 UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(userId).getData(); Assert.notNull(userInfoVo, "用户{}不存在", userId); Integer isVip = userInfoVo.getIsVip(); //4.2 默认设置需要进一步确定购买情况标识:默认false Boolean isNeedCheckPayStatus = false; //4.2.1 如果专辑付费类型 VIP免费 if (SystemConstant.ALBUM_PAY_TYPE_VIPFREE.equals(payType)) { //当前用户为普通用户或VIP会员过期 if (isVip.intValue() == 0) { isNeedCheckPayStatus = true; } if (isVip.intValue() == 1 && new Date().after(userInfoVo.getVipExpireTime())) { isNeedCheckPayStatus = true; } } //4.2.2 如果专辑付费类型 付费 if (SystemConstant.ALBUM_PAY_TYPE_REQUIRE.equals(payType)) { //当前用户为普通用户或VIP会员过期 isNeedCheckPayStatus = true; } if (isNeedCheckPayStatus) { //4.3 进一步确定用户是否购买专辑或声音-远程调用用户服务获取本页中专辑或者声音购买情况 //本页中需要检查购买情况声音列表,过滤掉当前页免费试听声音 List<AlbumTrackListVo> needCheckTrackList = pageInfo.getRecords().stream() .filter(albumTrackListVo -> albumTrackListVo.getOrderNum() > albumInfo.getTracksForFree()) .collect(Collectors.toList()); //本页中需要检查购买情况声音ID列表,过滤掉当前页免费试听声音 List<Long> needCheckTrackIdList = needCheckTrackList.stream() .map(albumTrackListVo -> albumTrackListVo.getTrackId()) .collect(Collectors.toList()); Map<Long, Integer> userPayStatusTrackMap = userFeignClient.userIsPaidTrack(userId, albumId, needCheckTrackIdList).getData(); //4.4 循环当前页中声音列表-跟返回用户购买情况声音集合逐一判断 needCheckTrackList.stream().forEach(needCheckTrack -> { Integer payStatus = userPayStatusTrackMap.get(needCheckTrack.getTrackId()); if (payStatus.intValue() == 0) { //4.5 某个声音用户未购买,将设置付费标识 isShowPaidMark:true needCheckTrack.setIsShowPaidMark(true); } }); } } return pageInfo; } ``` **TrackInfoMapper接口**:条件必须是当前已经开放并且是审核通过状态的数据,并且还需要获取到声音的播放量以及评论数量 ```java /** * 查询指定专辑下包含声音列表 * * @param pageInfo * @param albumId * @return */ Page<AlbumTrackListVo> getAlbumTrackPage(Page<AlbumTrackListVo> pageInfo, @Param("albumId") Long albumId); ``` **TrackInfoMapper.xml** 映射文件 动态SQL ```sql #分页查询指定专辑下包含声音列表(包含统计信息) select * from track_info where album_id = 307; select * from track_info where album_id = 307 and id = 16289; select * from track_stat where track_id = 16289; select ti.id trackId, ti.track_title trackTitle, ti.media_duration mediaDuration, ti.order_num orderNum, ti.create_time createTime, max(if(ts.stat_type='0701', ts.stat_num, 0)) playStatNum, max(if(ts.stat_type='0702', ts.stat_num, 0)) collectStatNum, max(if(ts.stat_type='0703', ts.stat_num, 0)) praiseStatNum, max(if(ts.stat_type='0704', ts.stat_num, 0)) commentStatNum from track_info ti left join track_stat ts on ts.track_id = ti.id where ti.album_id = 307 and ti.is_deleted = 0 group by ti.id order by ti.order_num ``` ```sql <!--分页获取专辑下声音列表--> <select id="getAlbumTrackPage" resultType="com.atguigu.tingshu.vo.album.AlbumTrackListVo"> select ti.id trackId, ti.track_title, ti.media_duration, ti.order_num, ti.create_time, max(if(stat.stat_type='0701', stat.stat_num, 0)) playStatNum, max(if(stat.stat_type='0702', stat.stat_num, 0)) collectStatNum, max(if(stat.stat_type='0703', stat.stat_num, 0)) praiseStatNum, max(if(stat.stat_type='0704', stat.stat_num, 0)) commentStatNum from track_info ti left join track_stat stat on stat.track_id = ti.id where ti.album_id = #{albumId} and ti.is_deleted = 0 group by ti.id order by ti.order_num </select> ``` 测试: - 手动增加用户购买专辑记录:**user_paid_album** - 手动增加用户购买声音记录:**user_paid_track** - 手动修改VIP会员:**user_info** 情况一:未登录情况,专辑付费类型:VIP免费 付费 查看声音列表->试听声音免费+其余都需要展示付费标识 情况二:登录情况 - 普通用户 - 免费 全部免费 - VIP付费 试听声音免费+用户购买过专辑/声音,未购买展示付费标识 - 付费:试听声音免费+用户购买过专辑/声音,未购买展示付费标识 - VIP用户 - 免费 全部免费 - VIP付费 全部免费 - 付费:试听声音免费+用户购买过专辑/声音,未购买展示付费标识 时间处理: ```java @Data @Schema(description = "UserInfoVo") public class UserInfoVo implements Serializable { @Schema(description = "用户id") private Long id; @Schema(description = "微信openId") private String wxOpenId; @Schema(description = "nickname") private String nickname; @Schema(description = "主播用户头像图片") private String avatarUrl; @Schema(description = "用户是否为VIP会员 0:普通用户 1:VIP会员") private Integer isVip; @Schema(description = "当前VIP到期时间,即失效时间") @DateTimeFormat( pattern = "yyyy-MM-dd" ) @JsonFormat( shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "GMT+8" ) @JsonDeserialize private Date vipExpireTime; } ``` # 2、MongoDB文档型数据库 详情见:**第6章 MongoDB入门.md** **播放进度**对应的实体类: ```java @Data @Schema(description = "UserListenProcess") @Document public class UserListenProcess { @Schema(description = "id") @Id private String id; @Schema(description = "用户id") private Long userId; @Schema(description = "专辑id") private Long albumId; @Schema(description = "声音id,声音id为0时,浏览的是专辑") private Long trackId; @Schema(description = "相对于音频开始位置的播放跳出位置,单位为秒。比如当前音频总时长60s,本次播放到音频第25s处就退出或者切到下一首,那么break_second就是25") private BigDecimal breakSecond; @Schema(description = "是否显示") private Integer isShow; @Schema(description = "创建时间") private Date createTime; @Schema(description = "更新时间") private Date updateTime; } ``` # 3、声音详情 ![详情-获取播放记录进度](assets/详情-获取播放记录进度.gif) ## 3.1 获取声音播放进度 在播放声音的时候,会有触发一个获取播放进度的控制器!因为页面每隔10s会自动触发一次保存功能,会将数据写入MongoDB中。所以我们直接从MongoDB中获取到上一次声音的播放时间即可! ![](assets/tingshu013.png) > YAPI接口:http://192.168.200.6:3000/project/11/interface/api/71 在 `service-user` 微服务的 **UserListenProcessApiController** 控制器中添加 ```java /** * 获取当前用户收听声音播放进 * * @param trackId * @return */ @GuiGuLogin(required = false) @Operation(summary = "获取当前用户收听声音播放进度") @GetMapping("/userListenProcess/getTrackBreakSecond/{trackId}") public Result<BigDecimal> getTrackBreakSecond(@PathVariable Long trackId) { Long userId = AuthContextHolder.getUserId(); if (userId != null) { BigDecimal breakSecond = userListenProcessService.getTrackBreakSecond(userId, trackId); return Result.ok(breakSecond); } return Result.ok(); } ``` **UserListenProcessService接口**: ```java /** * 获取当前用户收听声音播放进度 * @param userId 用户ID * @param trackId 声音ID * @return */ BigDecimal getTrackBreakSecond(Long userId, Long trackId); ``` **UserListenProcessServiceImpl**实现类: ```java package com.atguigu.tingshu.user.service.impl; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.IdUtil; import com.alibaba.fastjson.JSON; import com.atguigu.tingshu.common.constant.KafkaConstant; import com.atguigu.tingshu.common.constant.RedisConstant; import com.atguigu.tingshu.common.constant.SystemConstant; import com.atguigu.tingshu.common.service.KafkaService; import com.atguigu.tingshu.common.util.MongoUtil; import com.atguigu.tingshu.model.user.UserListenProcess; import com.atguigu.tingshu.user.service.UserListenProcessService; import com.atguigu.tingshu.vo.album.TrackStatMqVo; import com.atguigu.tingshu.vo.user.UserListenProcessVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Date; import java.util.concurrent.TimeUnit; @Service @SuppressWarnings({"all"}) public class UserListenProcessServiceImpl implements UserListenProcessService { @Autowired private MongoTemplate mongoTemplate; /** * 获取当前用户收听声音播放进度 * * @param userId 用户ID * @param trackId 声音ID * @return */ @Override public BigDecimal getTrackBreakSecond(Long userId, Long trackId) { //1.构建查询条件 Query query = new Query(); query.addCriteria(Criteria.where("userId").is(userId).and("trackId").is(trackId)); //2.执行查询播放进度 UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId)); if (userListenProcess != null) { return userListenProcess.getBreakSecond(); } return new BigDecimal("0.00"); } } ``` ![image-20240307200116030](assets/image-20240307200116030.png) ## 3.2 更新播放进度 页面每隔10秒左右更新播放进度. 1. 更新播放进度页面会传递 专辑Id ,秒数,声音Id 。后台会将这个三个属性封装到UserListenProcessVo 对象中。然后利用MongoDB进行存储到UserListenProcess实体类中! 2. 为了提高用户快速访问,将用户信息存储到缓存中。先判断当前用户Id 与 声音Id 是否存在,不存在的话才将数据存储到缓存,并且要发送消息给kafka。 3. kafka 监听消息并消费,更新专辑与声音的统计数据。 ### 3.2.1 更新MongoDB ![](assets/tingshu015.png) > YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/73 在 **UserListenProcessApiController** 控制器中添加 ```java /** * 更新当前用户收听声音播放进度 * @param userListenProcessVo * @return */ @GuiGuLogin(required = false) @Operation(summary = "更新当前用户收听声音播放进度") @PostMapping("/userListenProcess/updateListenProcess") public Result updateListenProcess(@RequestBody UserListenProcessVo userListenProcessVo){ Long userId = AuthContextHolder.getUserId(); if (userId != null) { userListenProcessService.updateListenProcess(userId, userListenProcessVo); } return Result.ok(); } ``` **UserListenProcessService**接口: ```java /** * 更新当前用户收听声音播放进度 * @param userId 用户ID * @param userListenProcessVo 播放进度信息 * @return */ void updateListenProcess(Long userId, UserListenProcessVo userListenProcessVo); ``` **UserListenProcessServiceImpl**实现类: ```java @Autowired private RedisTemplate redisTemplate; @Autowired private KafkaService kafkaService; /** * 更新当前用户收听声音播放进度 * * @param userId 用户ID * @param userListenProcessVo 播放进度信息 * @return */ @Override public void updateListenProcess(Long userId, UserListenProcessVo userListenProcessVo) { //1.根据用户ID+声音ID获取播放进度 Query query = new Query(); //1.1 设置查询条件 query.addCriteria(Criteria.where("userId").is(userId).and("trackId").is(userListenProcessVo.getTrackId())); //1.2 设置查询第一条记录(避免小程序暂停后恢复播放将积压更新进度请求并发发起,导致新增多条播放进度) query.limit(1); UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId)); if (userListenProcess == null) { //2.如果播放进度不存在-新增播放进度 userListenProcess = new UserListenProcess(); userListenProcess.setUserId(userId); userListenProcess.setAlbumId(userListenProcessVo.getAlbumId()); userListenProcess.setTrackId(userListenProcessVo.getTrackId()); userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond()); userListenProcess.setIsShow(1); userListenProcess.setCreateTime(new Date()); userListenProcess.setUpdateTime(new Date()); } else { //3.如果播放进度存在-更新进度 userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond()); userListenProcess.setUpdateTime(new Date()); } mongoTemplate.save(userListenProcess, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId)); //4.采用Redis提供set k v nx ex 确保在规定时间内(24小时/当日内)播放进度统计更新1次 String key = RedisConstant.USER_TRACK_REPEAT_STAT_PREFIX + userId + ":" + userListenProcessVo.getTrackId(); long ttl = DateUtil.endOfDay(new Date()).getTime() - System.currentTimeMillis(); Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, userListenProcess.getTrackId(), ttl, TimeUnit.MILLISECONDS); if (flag) { //5.如果是首次更新播放进度,发送消息到Kafka话题 //5.1 构建更新声音播放进度MQVO对象 TrackStatMqVo mqVo = new TrackStatMqVo(); //生成业务唯一标识,消费者端(专辑服务、搜索服务)用来做幂等性处理,确保一个消息只能只被处理一次 mqVo.setBusinessNo(IdUtil.fastSimpleUUID()); mqVo.setAlbumId(userListenProcessVo.getAlbumId()); mqVo.setTrackId(userListenProcessVo.getTrackId()); mqVo.setStatType(SystemConstant.TRACK_STAT_PLAY); mqVo.setCount(1); //5.2 发送消息到更新声音统计话题中 kafkaService.sendMessage(KafkaConstant.QUEUE_TRACK_STAT_UPDATE, JSON.toJSONString(mqVo)); } } ``` ### 3.2.2 更新MySQL统计信息 在`service-album` 微服务中添加监听消息: ```java package com.atguigu.tingshu.album.receiver; import com.alibaba.fastjson.JSON; import com.atguigu.tingshu.album.service.AlbumInfoService; import com.atguigu.tingshu.common.constant.KafkaConstant; import com.atguigu.tingshu.vo.album.TrackStatMqVo; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.stereotype.Component; /** * @author: atguigu * @create: 2023-12-19 15:31 */ @Slf4j @Component public class AlbumReceiver { @Autowired private AlbumInfoService albumInfoService; /** * 监听到更新声音统计信息 * 1.考虑消息幂等性 2.是否需要事务管理 * * @param record */ @KafkaListener(topics = KafkaConstant.QUEUE_TRACK_STAT_UPDATE) public void updateTrackStat(ConsumerRecord<String, String> record) { String value = record.value(); if (StringUtils.isNotBlank(value)) { log.info("[专辑服务],监听到更新声音统计消息:{}", value); TrackStatMqVo mqVo = JSON.parseObject(value, TrackStatMqVo.class); albumInfoService.updateTrackStat(mqVo); } } } ``` 在**TrackInfoService** 中添加接口 ```java /** * MQ监听更新声音统计信息 * @param mqVo */ void updateTrackStat(TrackStatMqVo mqVo); ``` 在**TrackInfoServiceImpl** 中添加实现 ```java @Autowired private AlbumStatMapper albumStatMapper; @Autowired private RedisTemplate redisTemplate; /** * MQ监听更新声音统计信息(包含:播放、收藏、点赞、评论) * * @param mqVo */ @Override @Transactional(rollbackFor = Exception.class) public void updateTrackStat(TrackStatMqVo mqVo) { //1.做幂等性处理,统一个消息只处理一次 采用set k(业务消息唯一标识) v NX EX String key = "mq:" + mqVo.getBusinessNo(); try { Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, mqVo.getBusinessNo(), 1, TimeUnit.HOURS); if (flag) { //2.更新声音统计信息 trackStatMapper.updateStat(mqVo.getTrackId(), mqVo.getStatType(), mqVo.getCount()); //3.更新专辑统计信息(播放量、评论量只要声音+1,对应专辑也得+1) if (SystemConstant.TRACK_STAT_PLAY.equals(mqVo.getStatType())) { albumStatMapper.updateStat(mqVo.getAlbumId(), SystemConstant.ALBUM_STAT_PLAY, mqVo.getCount()); } if (SystemConstant.TRACK_STAT_COMMENT.equals(mqVo.getStatType())) { albumStatMapper.updateStat(mqVo.getAlbumId(), SystemConstant.ALBUM_STAT_COMMENT, mqVo.getCount()); } } } catch (Exception e) { //如果更新数据库发送异常,事务会进行回滚,下次再次投递消息允许继续处理统一个消息 redisTemplate.delete(key); throw new RuntimeException(e); } } ``` **TrackStatMapper**.java 添加方法 ```java package com.atguigu.tingshu.album.mapper; import com.atguigu.tingshu.model.album.TrackStat; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.*; @Mapper public interface TrackStatMapper extends BaseMapper<TrackStat> { /** * 更新声音统计信息 * @param trackId 声音ID * @param statType 统计类型 * @param count 数量 */ @Update("update track_stat set stat_num = stat_num + #{count} where track_id = #{trackId} and stat_type = #{statType}") void updateStat(@Param("trackId") Long trackId, @Param("statType") String statType, @Param("count") Integer count); } ``` **AlbumStatMapper**.java 接口添加 ```java package com.atguigu.tingshu.album.mapper; import com.atguigu.tingshu.model.album.AlbumStat; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Update; @Mapper public interface AlbumStatMapper extends BaseMapper<AlbumStat> { @Update("update album_stat set stat_num = stat_num + #{count} where album_id = #{albumId} and stat_type = #{statType}") void updateStat(@Param("albumId") Long albumId, @Param("statType") String statType, @Param("count") Integer count); } ``` ## 3.3 专辑上次播放专辑声音 ![image-20231012111356796](assets/image-20231012111356796.png) 我们需要根据用户Id 来获取播放记录 ,需要获取到专辑Id 与声音Id 封装到map中然后返回数据即可! > YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/83 控制器 **UserListenProcessApiController** ```java /** * 获取当前用户上次播放专辑声音记录 * * @return */ @GuiGuLogin @GetMapping("/userListenProcess/getLatelyTrack") public Result<Map<String, Long>> getLatelyTrack() { Long userId = AuthContextHolder.getUserId(); return Result.ok(userListenProcessService.getLatelyTrack(userId)); } ``` **UserListenProcessService接口:** ```java /** * 获取用户最近一次播放记录 * @param userId * @return */ Map<String, Long> getLatelyTrack(Long userId); ``` **UserListenProcessServiceImpl实现类**: ```java /** * 获取用户最近一次播放记录 * * @param userId * @return */ @Override public Map<String, Long> getLatelyTrack(Long userId) { //根据用户ID查询播放进度集合,按照更新时间倒序,获取第一条记录 //1.构建查询条件对象 Query query = new Query(); //1.1 封装用户ID查询条件 query.addCriteria(Criteria.where("userId").is(userId)); //1.2 按照更新时间排序 query.with(Sort.by(Sort.Direction.DESC, "updateTime")); //1.3 只获取第一条记录 query.limit(1); //2.执行查询 UserListenProcess listenProcess = mongoTemplate.findOne(query, UserListenProcess.class, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId)); if (listenProcess != null) { //封装响应结果 Map<String, Long> mapResult = new HashMap<>(); mapResult.put("albumId", listenProcess.getAlbumId()); mapResult.put("trackId", listenProcess.getTrackId()); return mapResult; } return null; } ``` ## 3.4 获取声音统计信息 ![](assets/tingshu014.png) > YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/75 统计声音需要更新的数据如下,我们将数据封装到一个实体类中便于操作 ```java @Data @Schema(description = "用户声音统计信息") public class TrackStatVo { @Schema(description = "播放量") private Integer playStatNum; @Schema(description = "订阅量") private Integer collectStatNum; @Schema(description = "点赞量") private Integer praiseStatNum; @Schema(description = "评论数") private Integer commentStatNum; //该属性需要修改 } ``` 在**TrackInfoApiController** 控制器中添加 ```java /** * 根据声音ID,获取声音统计信息 * @param trackId * @return */ @Operation(summary = "根据声音ID,获取声音统计信息") @GetMapping("/trackInfo/getTrackStatVo/{trackId}") public Result<TrackStatVo> getTrackStatVo(@PathVariable Long trackId){ return Result.ok(trackInfoService.getTrackStatVo(trackId)); } ``` **TrackInfoService接口**: ```java /** * 根据声音ID,查询声音统计信息 * @param trackId * @return */ TrackStatVo getTrackStatVo(Long trackId); ``` **TrackInfoServiceImpl实现类**: ```java /** * 根据声音ID,查询声音统计信息 * @param trackId * @return */ @Override public TrackStatVo getTrackStatVo(Long trackId) { return trackInfoMapper.getTrackStatVo(trackId); } ``` **TrackInfoMapper**.java ```java /** * 获取声音统计信息 * @param trackId * @return */ @Select("select\n" + " track_id,\n" + " max(if(stat_type='0701', stat_num, 0)) playStatNum,\n" + " max(if(stat_type='0702', stat_num, 0)) collectStatNum,\n" + " max(if(stat_type='0703', stat_num, 0)) praiseStatNum,\n" + " max(if(stat_type='0704', stat_num, 0)) commentStatNum\n" + " from track_stat where track_id = #{trackId} and is_deleted=0\n" + "group by track_id") TrackStatVo getTrackStatVo(@Param("trackId") Long trackId); ``` **SQL** ```sql # 根据声音ID查询指定声音统计信息 playStatNum collectStatNum praiseStatNum commentStatNum select track_id, max(if(stat_type='0701', stat_num, 0)) playStatNum, max(if(stat_type='0702', stat_num, 0)) collectStatNum, max(if(stat_type='0703', stat_num, 0)) praiseStatNum, max(if(stat_type='0704', stat_num, 0)) commentStatNum from track_stat where track_id = 49162 and is_deleted=0 group by track_id ``` # 4、更新Redis排行榜 手动调用一次更新,查看排行榜。后续会整合xxl-job 分布式定时任务调度框架做定时调用。 ![详情-排行榜](assets/详情-排行榜.gif) > YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/77 `service-album `微服务中**BaseCategoryApiController**控制器中添加 ```java /** * 查询所有一级分类列表 * @return */ @Operation(summary = "查询所有一级分类列表") @GetMapping("/category/findAllCategory1") public Result<List<BaseCategory1>> getAllCategory1() { return Result.ok(baseCategoryService.list()); } ``` **AlbumFeignClient** ```java /** * 查询所有一级分类列表 * @return */ @GetMapping("/category/findAllCategory1") public Result<List<BaseCategory1>> getAllCategory1(); ``` **AlbumDegradeFeignClient熔断类**: ```java @Override public Result<List<BaseCategory1>> getAllCategory1() { log.error("[专辑模块Feign调用]getAllCategory1异常"); return null; } ``` > YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/79 在**SearchApiController** 中添加控制器 ```java /** * 为定时更新首页排行榜提供调用接口 * @return */ @Operation(summary = "为定时更新首页排行榜提供调用接口") @GetMapping("/albumInfo/updateLatelyAlbumRanking") public Result updateLatelyAlbumRanking(){ searchService.updateLatelyAlbumRanking(); return Result.ok(); } ``` **SearchService**接口: ```java /** * 获取不同分类下不同排序方式榜单专辑列表 */ void updateLatelyAlbumRanking(); ``` **SearchServiceImpl实现类:** ```java @Autowired private RedisTemplate redisTemplate; /** * 获取不同分类下不同排序方式榜单专辑列表 */ @Override public void updateLatelyAlbumRanking() { try { //1.远程调用专辑服务获取所有1级分类列表 List<BaseCategory1> category1List = albumFeignClient.getdAllCategory1().getData(); Assert.notNull(category1List, "一级分类为空"); //2.循环遍历1级分类列表,获取该分类下5种不同排序方式榜单专辑 for (BaseCategory1 baseCategory1 : category1List) { Long category1Id = baseCategory1.getId(); //3.在处理当前1级分类中,再次循环5种不同排序方式得到具体榜单数据 //3.1 声明排序方式数组 String[] rankingDimensionArray = new String[]{"hotScore", "playStatNum", "subscribeStatNum", "buyStatNum", "commentStatNum"}; for (String rankingDimension : rankingDimensionArray) { //3.2 调用ES检索接口获取榜单数据 SearchResponse<AlbumInfoIndex> searchResponse = elasticsearchClient.search( s -> s.index(INDEX_NAME) .query(q -> q.term(t -> t.field("category1Id").value(category1Id))) .sort(sort -> sort.field(f -> f.field(rankingDimension).order(SortOrder.Desc))) .size(10) , AlbumInfoIndex.class ); //3.3 获取当前分类下某个排序方式榜单专辑列表 List<Hit<AlbumInfoIndex>> hits = searchResponse.hits().hits(); if (CollectionUtil.isNotEmpty(hits)) { List<AlbumInfoIndex> list = hits.stream().map(hit -> hit.source()).collect(Collectors.toList()); //4.将榜单专辑列表存入Redis-Hash中 //4.1 声明Redis排行榜Hash接口 Key 形式:前缀+1级分类ID field:排序方式 val:榜单列表 String key = RedisConstant.RANKING_KEY_PREFIX + category1Id; //4.2 将当前分类榜单数据放入Redis中 redisTemplate.opsForHash().put(key, rankingDimension, list); } } } } catch (Exception e) { log.error("[搜索服务]更新排行榜异常:{}", e); throw new RuntimeException(e); } } ``` # 5、获取排行榜 ![image-20231012114420751](assets/image-20231012114420751.png) 点击排行榜的时候,能看到获取排行榜的地址 排行榜:key=ranking:category1Id field = hotScore 或 playStatNum 或 subscribeStatNum 或 buyStatNum 或albumCommentStatNum value=List<AlbumInfoIndexVo> ![](assets/tingshu016.png) > YAPI接口地址:http://192.168.200.6:3000/project/11/interface/api/81 **SearchApiController** 控制器中添加 ```java /** * 获取指定1级分类下不同排序方式榜单列表-从Redis中获取 * @param category1Id * @param dimension * @return */ @Operation(summary = "获取指定1级分类下不同排序方式榜单列表") @GetMapping("/albumInfo/findRankingList/{category1Id}/{dimension}") public Result<List<AlbumInfoIndex>> getRankingList(@PathVariable Long category1Id, @PathVariable String dimension){ List<AlbumInfoIndex> list = searchService.getRankingList(category1Id, dimension); return Result.ok(list); } ``` **SearchService**接口: ```java /** * 获取指定1级分类下不同排序方式榜单列表-从Redis中获取 * @param category1Id * @param dimension * @return */ List<AlbumInfoIndex> getRankingList(Long category1Id, String dimension); ``` **SearchServiceImpl实现类**: ```java /** * 获取指定1级分类下不同排序方式榜单列表-从Redis中获取 * * @param category1Id * @param dimension * @return */ @Override public List<AlbumInfoIndex> getRankingList(Long category1Id, String dimension) { //1.构建分类排行榜Hash结构Key String key = RedisConstant.RANKING_KEY_PREFIX + category1Id; //2.获取Redis中hash结构中value Boolean flag = redisTemplate.opsForHash().hasKey(key, dimension); if (flag) { List<AlbumInfoIndex> list = (List) redisTemplate.opsForHash().get(key, dimension); return list; } return null; } ``` 结合上面的内容介绍断点续播的实现思路,不需要给出代码
07-11
我前段时间写了一个python程序,用于抓取自己闲鱼页面的商品信息,但是为了避免违规,我想重新编写一个程序,用于在阿奇索后台(开发指南:接入指南 1、接入流程 【开发者操作】登录后台申请AppIds。 入口:https://open.agiso.com/#/my/application/app-list 【开发者操作】申请到AppId后,开发者可以登录后台管理AppId,这里可以查看和更换AppSecret、更改推送url、更改授权回调url等。 入口:https://open.agiso.com/#/my/application/app-list 【商家操作】授权,方法有二: 1、输入开发者提供的AppId(相当于告诉Agiso,允许这个AppId通过Agiso开放平台获取或操作商家自己的订单数据),勾选相应要授权的权限。授权后会显示一个Token,将Token复制给开发者。 入口:https://aldsIdle.agiso.com/#/open/authorize 2、开发者如果有开发自动授权,则商家可以通过访问以下页面进行授权: 入口:https://aldsIdle.agiso.com/#/authorize?appId={$请替换为要授权的开发者的appId}&state=2233 【开发者操作】开发者得到各个商家授权给的Token,并使用Token调用接口。调用接口时,需要使用AppSecret进行签名,具体签名方法参见下文。 注意:开发者与商家,也可以是同一个人。 2、获取AccessToken详解 手动模式自动模式 将你的AppId告诉您的用户,用户通过在授权页面(https://aldsIdle.agiso.com/#/open/authorize) 进行授权。用户授权完成后,会获得一个AccessToken,让您的用户把该AccessToken发给你。 AccessToken的有效期和您的用户购买Agiso软件的使用时间一致。如果您的用户续费,那么AccessToken的有效期也会延长。 3、调用接口详解 调用任何一个API都必须把AccessToken 和 ApiVersion 添加到Header ,格式为"Authorization: Bearer access_token",其中Bearer后面有一个空格。同时还需传入以下公共参数: timestamp 是 Date 时间戳,例如:1468476350。API服务端允许客户端请求最大时间误差为10分钟。 sign 是 string API输入参数签名结果,签名算法参照下面的介绍。 注意:接口调用配额,20次/秒。 4、签名算法 【对所有API请求参数(包括公共参数和业务参数,但除去sign参数和byte[]类型的参数),根据参数名称的ASCII码表的顺序排序。如:foo=1, bar=2, foo_bar=3, foobar=4排序后的顺序是bar=2, foo=1, foo_bar=3, foobar=4。 将排序好的参数名和参数拼装在一起,根据上面的示例得到的结果为:bar2foo1foo_bar3foobar4。 把拼装好的字符串采用utf-8编码,在拼装的字符串前后加上app的secret后,使用MD5算法进行摘要,如:md5(secret+bar2foo1foo_bar3foobar4+secret); 5、Header设置示例代码 JavaC#PHP HttpPost httpPost = new org.apache.http.client.methods.HttpPost(url); httpPost.addHeader("Authorization","Bearer "+ accessToken); httpPost.addHeader("ApiVersion", "1"); 6、签名算法示例代码 JavaC#PHP Map<String, String> data = new HashMap<String, String>(); data.put("modifyTimeStart", "2016-07-13 10:44:30"); data.put("pageNo", "1"); data.put("pageSize", "20"); //timestamp 为调用Api的公共参数,详细说明参考接入指南 data.put("timestamp", '1468476350');//假设当前时间为2016/7/14 14:5:50 //对键排序 String[] keys = data.keySet().toArray(new String[0]); Arrays.sort(keys); StringBuilder query = new StringBuilder(); //头加入AppSecret ,假设AppSecret为****************** query.append(this.getClientSecret()); for (String key : keys) { String value = data.get(key); query.append(key).append(value); } //到这query的为******************modifyTimeStart2016-07-13 10:44:30pageNo1pageSize20timestamp1468476350 //尾加入AppSecret query.append(this.getClientSecret()); //query=******************modifyTimeStart2016-07-13 10:44:30pageNo1pageSize20timestamp1468476350****************** byte[] md5byte = encryptMD5(query.toString()); //sign 为调用Api的公共参数,详细说明参考接入指南 data.put("sign", byte2hex(md5byte)); //byte2hex(md5byte) = 935671331572EBF7F419EBB55EA28558 // Md5摘要 public byte[] encryptMD5(String data) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md5 = MessageDigest.getInstance("MD5"); return md5.digest(data.getBytes("UTF-8")); } public String byte2hex(byte[] bytes) { StringBuilder sign = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(bytes[i] & 0xFF); if (hex.length() == 1) { sign.append("0"); } sign.append(hex.toLowerCase()); } return sign.toString(); } 7、完整调用API示例代码 以下代码以调用LogisticsDummySend(更新发货状态)为例 JavaC#PHP public String LogisticsDummySend() { string accessToken = "*************"; string appSecret = "*************"; WebRequest apiRequest = WebRequest.Create("http://gw.api.agiso.com/aldsIdle/Trade/LogisticsDummySend"); apiRequest.Method = "POST"; apiRequest.ContentType = "application/x-www-form-urlencoded"; apiRequest.Headers.Add("Authorization", "Bearer " + accessToken); apiRequest.Headers.Add("ApiVersion", "1"); //业务参数 TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); var args = new Dictionary<string,string>() { {"tids","123456789,987465123"}, 注意 tids是示例参数实际参数要以当前文档上的入参为准!!! {"timestamp",Convert.ToInt64(ts.TotalSeconds).ToString()} }; args.Add("sign", Sign(args, appSecret)); //拼装POST数据 string postData = ""; foreach (var p in args) { if (!String.IsNullOrEmpty(postData)) { postData += "&"; } string tmpStr = String.Format("{0}={1}", p.Key, HttpUtility.UrlEncode(p.Value)); postData += tmpStr; } using (var sw = new StreamWriter(apiRequest.GetRequestStream())) { sw.Write(postData); } WebResponse apiResponse = null; try { apiResponse = apiRequest.GetResponse(); } catch (WebException we) { if (we.Status == WebExceptionStatus.ProtocolError) { apiResponse = (we.Response as HttpWebResponse); } else{ //TODO:处理异常 return ""; } } using(Stream apiDataStream = apiResponse.GetResponseStream()){ using(StreamReader apiReader = new StreamReader(apiDataStream, Encoding.UTF8)){ string apiResult = apiReader.ReadToEnd(); apiReader.Close(); apiResponse.Close(); return apiResult; } } } //参数签名 public string Sign(IDictionary<string,string> args, string ClientSecret) { IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(args, StringComparer.Ordinal); string str = ""; foreach (var m in sortedParams) { str += (m.Key + m.Value); } //头尾加入AppSecret str = ClientSecret + str + ClientSecret; var encodeStr = MD5Encrypt(str); return encodeStr; } //Md5摘要 public static string MD5Encrypt(string text) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] fromData = System.Text.Encoding.UTF8.GetBytes(text); byte[] targetData = md5.ComputeHash(fromData); string byte2String = null; for (int i = 0; i < targetData.Length; i++) { byte2String += targetData[i].ToString("x2"); } return byte2String; })作为API接入商家后台,我想要获取我自己的商品数据:(# helps.py(仅仅作为功能参考,可以根据实际编写需要改写) import os def display_help(): """显示帮助信息""" print(""" 商品信息抓取工具 v1.0 ========================== 使用方法: python main.py [选项] 选项: -u, --url URL 商品URL -o, --output PATH 输出文件路径(.docx) -f, --file FILE 批量任务文件路径 -t, --threads N 并发线程数(默认:2) -d, --debug 启用调试模式 -v, --verbose 显示详细输出 -h, --help 显示帮助信息 批量任务文件格式: URL | 输出文件名称 以#开头的行默认为注释,将不会进行任何的处理 示例: https://2.taobao.com/item?id=123 | item1.docx https://2.taobao.com/item?id=456 | item2.docx 输出文件: 1. Word文档(.docx) - 包含商品标题、描述和图片 2. Excel报告(.xlsx) - 包含word文档标题和元数据(价格,商品标题等) 日志文件: xianyu_scraper.log - 包含详细运行日志 依赖库: pip~=25.1.1 requests==2.32.4 beautifulsoup4==4.12.3 python-docx==1.1.0 pandas==2.3.1 openpyxl==3.1.5 fake-useragent==2.2.0 htmldocx==0.0.6 pillow==11.3.0 selenium==4.34.2 webdriver-manager==4.0.2 tqdm==4.67.1(进度条) """) def show_banner(): """显示程序横幅""" print(r""" 商品信息抓取工具 v1.0 ============================================================================== """),现在请为我编写程序,并且给我一个详细的接入阿奇索后台的步骤
07-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值