123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
- <?php
- namespace App\Servers;
- use App\Events\NumEvent;
- use App\Jobs\IndentNumJob;
- use App\Models\IndentNum;
- use App\Models\Menu;
- use App\Models\MenuUrl;
- use App\Models\Permission;
- use App\Models\Role;
- use App\Models\RolePermission;
- use App\Models\User;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Redis;
- /**
- * Redis数据缓存类
- */
- class IndentNumServer
- {
- /**
- * 单列对象
- * @var
- */
- static $server;
- private $key_name = 'ac_num';
- private $max_num;
- private function __construct()
- {
- $this->max_num=env('CODE_NUM_LENGTH',100);
- }
- /**
- * 创建对象
- * @return IndentNumServer
- */
- static function creatServer()
- {
- if (empty(self::$server)) {
- self::$server = new IndentNumServer();
- }
- return self::$server;
- }
- /**
- * 获取最新编号
- * @param $type
- * @param int $length
- * @return string
- */
- function getIndentNum($type, $length = 0)
- {
- $redis_name = $this->key_name . '_' . $type;
- // event(new NumEvent($type));
- $row=RedisDataServer::creatServer()->getData($redis_name.'_data','json');
- if(empty($row)){
- $row = IndentNum::where('type', $type)->first()->toArray();
- }
- $redis_num=$row['number']+1;
- RedisDataServer::creatServer()->setData($redis_name.'_data',$row,'json',60);
- $row['digits'] = $length > 0 ? $length : $row['digits'];
- $date = date("Ymd");
- if (!$redis_num) {
- if ($row['is_date'] == 1) {
- $num = sprintf("%0{$row['digits']}s", $row['number'] + 1);
- $new_cod = $date . $num;
- } else {
- $new_cod = sprintf("%0{$row['digits']}s", $row['number'] + 1);
- }
- } else {
- if ($row['is_date'] == 1) {
- $num = sprintf("%0{$row['digits']}s", $redis_num);
- $new_cod = $date . $num;
- } else {
- $new_cod = sprintf("%0{$row['digits']}s", $redis_num);
- }
- }
- IndentNum::where('id',$row['id'])->increment('number');
- return $row['code_str'] . $new_cod;
- }
- /**
- * 验证队列的数据并自动生成
- * @param $type
- */
- function verifyNum($type)
- {
- $redis_name = $this->key_name . '_' . $type;
- $key_num = RedisDataServer::creatServer()->getQueueList($redis_name);
- if ($key_num <35) {
- //开启事务,并启动悲观锁
- DB::beginTransaction();
- $row = IndentNum::where('type', $type)->select(['id','number','max_num'])->lockForUpdate()->first();
- $max_num = $row->{'number'} > $row->{'max_num'} ? $row->{'number'} : $row->{'max_num'};
- $num_arr=range($max_num+1,$max_num+100);
- // $num_arr=array_reverse($num_arr);
- RedisDataServer::creatServer()->addQueue($redis_name,$num_arr);
- IndentNum::where('id',$row->{'id'})->update(['max_num'=>$max_num+100]);
- DB::commit();
- }
- }
- }
|