MakeReport.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace app\common\library;
  3. use think\Env;
  4. /**
  5. * 报表生成服务类
  6. * Class MakeReport
  7. */
  8. class MakeReport{
  9. private $_redis = null;
  10. public function __construct(){
  11. if(extension_loaded('redis')) {
  12. $this->_redis = new \Redis();
  13. $this->_redis->connect(Env::get('redis.host', '127.0.0.1'), Env::get('redis.port', 6379));
  14. if (Env::get('redis.password', '')) {
  15. $this->_redis->auth(Env::get('redis.password', ''));
  16. }
  17. $this->_redis->select(Env::get('redis.select', 0));
  18. } else {
  19. throw Exception('请开启redis扩展');
  20. }
  21. }
  22. /**
  23. * 添加报表生成任务
  24. * @param $action string 和python协商好的名称用来识别哪个报表
  25. * @param $sql
  26. * @param $uid int 用户id
  27. * @param $extend array 扩展参数
  28. * @param $count int sql查询结果总条数
  29. * @param int $expire 相同任务多久内不重复生成
  30. *
  31. * @return boolean true:提交报表任务成功 ;false:提交报表失败
  32. */
  33. public function addTask($action, $sql, $uid, $extend = ['is_show'=>false], $count = 0, $expire = 3600){
  34. $task_data = array(
  35. 'action' => $action,
  36. 'sql' => $sql,
  37. 'uid' => $uid,
  38. 'time' => request()->time(),
  39. 'extend' => $extend,
  40. 'count' => $count
  41. );
  42. $task_unique_id = strtolower(md5(sprintf(
  43. '%s|%s|%s|%s',
  44. $task_data['uid'],
  45. $task_data['action'],
  46. $task_data['sql'],
  47. json_encode($task_data['extend'])
  48. )));
  49. $task_unique_id = config('MAKE_REPORT_UNIQUE_KEY_PRE') . $task_unique_id;
  50. $has_task = $this->_redis->get($task_unique_id);
  51. // 防止重复生成报表
  52. if(empty($has_task)) {
  53. $this->_redis->lpush(config('MAKE_REPORT_KEY'), json_encode($task_data));
  54. $this->_redis->setex($task_unique_id, $expire,1);
  55. return true;
  56. }
  57. else{
  58. return false;
  59. }
  60. }
  61. }