Commit d2f95f4a by 杨树贤

根据前端接口更改对应的红包获取列表服务,加上redis缓存操作

parent c966fb3b
...@@ -24,9 +24,13 @@ SYSTEM_NAME=IC业务助手福利中心服务 ...@@ -24,9 +24,13 @@ SYSTEM_NAME=IC业务助手福利中心服务
//laravels监听IP和端口 //laravels监听IP和端口
LARAVELS_LISTEN_IP=0.0.0.0 LARAVELS_LISTEN_IP=0.0.0.0
LARAVELS_LISTEN_PORT=61009 LARAVELS_LISTEN_PORT=61009
<<<<<<< HEAD
REDIS_HOST=192.168.1.235 REDIS_HOST=192.168.1.235
REDIS_PASSWORD=icDb29mLy2s REDIS_PASSWORD=icDb29mLy2s
REDIS_PORT=6379 REDIS_PORT=6379
REDIS_READ_HOST=192.168.1.235
REDIS_READ_PASSWORD=icDb29mLy2s
REDIS_READ_PORT=6379
...@@ -42,7 +42,11 @@ class IntegralsController extends Controller ...@@ -42,7 +42,11 @@ class IntegralsController extends Controller
$page = $request->has('page') ? $request->page : self::DEFAULT_PAGE; $page = $request->has('page') ? $request->page : self::DEFAULT_PAGE;
$pageSize = $request->has('page_size') ? $request->page_size : self::DEFAULT_PAGE_SIZE; $pageSize = $request->has('page_size') ? $request->page_size : self::DEFAULT_PAGE_SIZE;
if ($request->has('is_api') && $request->is_api) {
$result = $integral->getIntegralListForApi();
} else {
$result = $integral->getIntegralList($page, $pageSize, $filter); $result = $integral->getIntegralList($page, $pageSize, $filter);
}
return $this->Export(0, 'ok', $result); return $this->Export(0, 'ok', $result);
} }
...@@ -147,9 +151,10 @@ class IntegralsController extends Controller ...@@ -147,9 +151,10 @@ class IntegralsController extends Controller
*/ */
public function batchUpdateStatus(Request $request, Integral $integral) public function batchUpdateStatus(Request $request, Integral $integral)
{ {
$ids = $request->ids; $ids = $request->get('ids');
if (!is_array($ids)) { if (!is_array($ids)) {
return Log::Info('批量修改参数不是数组'); Log::Info('批量修改参数不是数组');
return $this->Export(44, '批量修改参数不是数组');
} }
$status = $request->status; $status = $request->status;
$data = ['status' => $status, 'update_time' => time()]; $data = ['status' => $status, 'update_time' => time()];
......
...@@ -24,8 +24,8 @@ class UserIntegralsController extends Controller ...@@ -24,8 +24,8 @@ class UserIntegralsController extends Controller
*/ */
public function show(Request $request) public function show(Request $request)
{ {
$id = $request->id; $userId = $request->get('id');
$integral = UserIntegral::where('user_id', $id)->first(); $integral = UserIntegral::where('user_id', $userId)->first();
$integral = $integral ?: []; $integral = $integral ?: [];
return $this->Export(0, 'ok', ['data' => $integral]); return $this->Export(0, 'ok', ['data' => $integral]);
......
...@@ -7,7 +7,9 @@ namespace App\Models; ...@@ -7,7 +7,9 @@ namespace App\Models;
use App\Http\Filters\QueryFilter; use App\Http\Filters\QueryFilter;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use phpDocumentor\Reflection\DocBlock\Tags\Reference\Fqsen;
//活动红包模型
class Integral extends Model class Integral extends Model
{ {
public $timestamps = false; public $timestamps = false;
...@@ -24,37 +26,195 @@ class Integral extends Model ...@@ -24,37 +26,195 @@ class Integral extends Model
return $filters->apply($query); return $filters->apply($query);
} }
//获取活动红包列表
public function getIntegralList($page, $pageSize, $filter) public function getIntegralList($page, $pageSize, $filter)
{ {
$integrals = Integral::filter($filter) $integrals = Integral::filter($filter)
->page($page, $pageSize) ->page($page, $pageSize)
->orderBy('id', 'desc')
->get()->toArray(); ->get()->toArray();
$count = Integral::count(); $count = Integral::filter($filter)->count();
return ['data' => $integrals, 'count' => $count]; return ['data' => $integrals, 'count' => $count];
} }
//获取红包活动列表,给API使用
public function getIntegralListForApi()
{
//先从redis里面查询是否有列表,没有的话从MySQL里面取出并且放入redis
$redis = new RedisModel();
$integrals = $this->getIntegralListFromRedis();
$count = 0;
if (!$integrals) {
$result = $this->addIntegralListToRedis();
if (!$result) {
ErrorLog(ErrorCode(18, '5'), '写入红包活动列表到Redis失败');
$count = Integral::where('status', 1)->count();
}
} else {
$count = $redis->hlen('ic_welfare_integrals');
}
$integrals = arraySequence($integrals,'id','SORT_ASC');
return ['data' => array_values($integrals), 'count' => $count];
}
//从redis查询出红包列表
public function getIntegralListFromRedis()
{
$redis = new RedisModel();
$integrals = $redis->hgetall('ic_welfare_integrals');
$integrals = array_map(function ($value) {
return json_decode($value, true);
}, $integrals);
return $integrals;
}
//添加红包列表到Redis
public function addIntegralListToRedis()
{
$integrals = Integral::where('status', 1)
->get()->toArray();
$redis = new RedisModel();
//转换数据存储到Redis的哈希类型
$data = [];
foreach ($integrals as $key => $integral) {
$data[$integral['id']] = json_encode($integral);
}
//这里如果没有数据放到缓存了,直接删除key
if ($data) {
$result = $redis->hmset('ic_welfare_integrals', $data);
} else {
$result = $redis->del('ic_welfare_integrals');
}
return $result;
}
//添加单个红包
public function addIntegral($data = []) public function addIntegral($data = [])
{ {
$res = DB::table('integrals')->insert($data); $result = DB::transaction(function () use ($data) {
$id = DB::table('integrals')->insertGetId($data);
$data['update_time'] = 0;
$data['id'] = $id;
if (!$id) {
return false;
}
$result = $this->addIntegralToRedis($id, $data);
if ($result === false) {
throw new \Exception('新增红包活动缓存数据失败', ErrorCode(19, 5));
}
return $res; return true;
}, 5);
return $result;
} }
//添加单个红包活动到redis
public function addIntegralToRedis($id, $data)
{
$redis = new RedisModel();
$result = $redis->hset('ic_welfare_integrals', $id, json_encode($data));
return $result;
}
//更新单个红包活动
public function updateIntegral($id, $data = []) public function updateIntegral($id, $data = [])
{ {
$res = DB::table('integrals')->where('id', $id) $result = DB::transaction(function () use ($id, $data) {
$result = DB::table('integrals')->where('id', $id)
->update($data); ->update($data);
if (!$result) {
return false;
}
return $res; if ($result) {
$result = $this->changeIntegralsFromRedis([$id]);
if ($result === false) {
throw new \Exception('更新红包活动缓存数据失败', ErrorCode(20, 5));
}
}
return $result ? true : false;
}, 5);
return $result;
}
//更新Redis的单个红包活动
public function updateIntegralFromRedis($id, $data)
{
$redis = new RedisModel();
$integral = $redis->hget('ic_welfare_integrals', $id);
$result = false;
if ($integral) {
//为什么用array_merge,因为右边的数组的键值会覆盖左边的对应值
$data = array_merge(json_decode($integral, true), $data);
$result = $redis->hset('ic_welfare_integrals', $id, json_encode($data));
} }
return $result;
}
//更新可使用状态,要将redis的列表也更新
public function batchUpdateStatus($ids = [], $data = []) public function batchUpdateStatus($ids = [], $data = [])
{ {
$res = DB::table('integrals')->whereIn('id', $ids)->update($data); $result = DB::transaction(function () use ($ids, $data) {
$result = DB::table('integrals')->whereIn('id', $ids)->update($data);
if (!$result) {
return false;
}
$result = $this->changeIntegralsFromRedis($ids);
if ($result === false) {
throw new \Exception('更新部分红包信息到redis失败', ErrorCode(21, 5));
}
return $res; return true;
}, 5);
return $result;
}
//因为修改状态会涉及到不少信息的更变,所以直接重新更新有变化的数据(根据ids)
public function changeIntegralsFromRedis($ids = [])
{
if ($ids) {
$changedIntegrals = DB::table('integrals')
->whereIn('id', $ids)->get()->toArray();
$needDelete = $needUpdate = [];
foreach ($changedIntegrals as $key => $value) {
//判断是不是禁用,如果是禁用,就从redis里面删除
if (!$value->status) {
$needDelete[] = $value->id;
} else {
$needUpdate[$value->id] = json_encode($value);
}
}
$redis = new RedisModel();
if ($needDelete) {
$result = $redis->hdel('ic_welfare_integrals', $needDelete);
if ($result === false) {
return false;
}
}
if ($needUpdate) {
$result = $redis->hmset('ic_welfare_integrals', $needUpdate);
if ($result === false) {
return false;
}
}
return true;
}
return true;
} }
public function deleteIntegral($ids = []) public function deleteIntegral($ids = [])
......
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;
class RedisModel extends Model
{
const WRITE_CONNECT_METHOD = ['set', 'del', 'rpush','lpush', 'expire', 'hset', 'hmset', 'hdel','hsetnx','hincrby'];
private $read = [];
private $write = [];
public function __construct($ConnectWrite = 'default', $ConnectRead = 'read')
{
parent::__construct();
$this->read = Redis::connection($ConnectRead);
$this->write = Redis::connection($ConnectWrite);
}
public function __call($method, $args)
{
$cls = &$this;
$tmp = function($method, $args) use ($cls) {
if (strpos($method, 'pipeline_')) {//使用管道
$method = substr($method, 9);
if (in_array($method, $cls::WRITE_CONNECT_METHOD)) {
return $cls->write->pipeline(function ($pipe) use ($args) {
foreach ($args as $arg) {
$pipe->$method(...$arg);
}
});
} else {
try {
return $cls->read->pipeline(function ($pipe) use ($args) {
foreach ($args as $arg) {
$pipe->$method(...$arg);
}
});
} catch (ConnectionException $e) {
return $cls->write->pipeline(function ($pipe) use ($args) {
foreach ($args as $arg) {
$pipe->$method(...$arg);
}
});
}
}
} else {
if (in_array($method, $cls::WRITE_CONNECT_METHOD)) {
return $cls->write->$method(...$args);
} else {
try {
return $cls->read->$method(...$args);
} catch (ConnectionException $e) {
return $cls->write->$method(...$args);
}
}
}
};
try {
return $tmp($method, $args);
} catch (\Exception $e) {
dd($e);
return false;
}
// if (strpos($method, 'catch_') === 0) {
// $method = substr($method, 6);
// try {
// return $tmp($method, $args);
// } catch (\Exception $e) {
// return null;
// }
// } else {
// return $tmp($method, $args);
// }
}
}
...@@ -143,13 +143,13 @@ return [ ...@@ -143,13 +143,13 @@ return [
'host' => env('REDIS_HOST', '127.0.0.1'), 'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null), 'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379), 'port' => env('REDIS_PORT', 6379),
'database' => 0 'database' => 2
], ],
'read' =>[ 'read' =>[
'host' => env('REDIS_READ_HOST', ''), 'host' => env('REDIS_READ_HOST', ''),
'password' => env('REDIS_READ_PASSWORD', null), 'password' => env('REDIS_READ_PASSWORD', null),
'port' => env('REDIS_READ_PORT', 6379), 'port' => env('REDIS_READ_PORT', 6379),
'database' => 0 'database' => 2
] ]
], ],
......
25816 9058
\ No newline at end of file \ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment