index.ts 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import { v4 } from 'uuid'
  2. import { quoteServerRequest } from '@/services/socket/quote'
  3. import { sessionData } from '@/stores'
  4. import eventBus from '@/services/bus'
  5. import socket from '@/services/socket'
  6. /**
  7. * 订阅行情
  8. */
  9. export default new (class {
  10. /** 行情订阅列表 */
  11. private quoteSubscribeMap = new Map<string, string[]>()
  12. constructor() {
  13. // 接收行情服务断线重连成功通知
  14. eventBus.$on('QuoteServerReconnectNotify', () => {
  15. this.quoteSubscribe();
  16. })
  17. }
  18. /**
  19. * 开始行情订阅
  20. */
  21. private quoteSubscribe = () => {
  22. const subscribeData: Proto.QuoteReq[] = []
  23. this.quoteSubscribeMap.forEach((value) => {
  24. const item = value.map((code) => ({
  25. goodsCode: code,
  26. exchangeCode: 250,
  27. subState: 0
  28. }))
  29. subscribeData.push(...item)
  30. })
  31. if (subscribeData.length) {
  32. console.log('开始行情订阅', subscribeData)
  33. quoteServerRequest({
  34. data: subscribeData,
  35. success: (res) => {
  36. if (res.length) {
  37. console.log('行情订阅成功', res)
  38. } else {
  39. console.error('行情订阅失败')
  40. }
  41. },
  42. fail: (err) => {
  43. console.error('行情订阅失败', err)
  44. }
  45. })
  46. } else {
  47. // 没有订阅商品的时候,断开连接
  48. socket.closeQuoteServer()
  49. }
  50. }
  51. /**
  52. * 添加行情订阅
  53. * @param goodsCodes
  54. * @param key
  55. * @returns
  56. */
  57. addQuoteSubscribe = (goodsCodes: string[], key?: string) => {
  58. const uuid = key ?? v4()
  59. const value = this.quoteSubscribeMap.get(uuid) ?? []
  60. const start = () => {
  61. // 对相同 key 订阅的商品进行合并处理
  62. this.quoteSubscribeMap.set(uuid, [...value, ...goodsCodes])
  63. this.quoteSubscribe()
  64. }
  65. return {
  66. uuid,
  67. start,
  68. stop: () => {
  69. const flag = this.quoteSubscribeMap.delete(uuid)
  70. if (flag) {
  71. console.log('删除订阅', uuid)
  72. }
  73. if (sessionData.getLoginInfo('Token')) {
  74. this.quoteSubscribe()
  75. }
  76. return flag
  77. },
  78. }
  79. }
  80. /**
  81. * 删除行情订阅
  82. * @param keys
  83. */
  84. removeQuoteSubscribe = (...keys: string[]) => {
  85. if (keys.length) {
  86. keys.forEach((key) => {
  87. if (this.quoteSubscribeMap.delete(key)) {
  88. console.log('删除订阅', key)
  89. }
  90. })
  91. } else {
  92. console.log('取消订阅')
  93. this.quoteSubscribeMap.clear()
  94. }
  95. this.quoteSubscribe()
  96. }
  97. })