月度归档:2021年03月

使用阿里云的Redis时,Laravel把Job发布到Queue失效的问题

又是一个坑人的大坑。

之前遇到的问题是在设置密码的时候,不是用户名和密码,需要把用户名和密码用冒号串起来写进去进行认证。

我们用的是阿里去的ecs和redis,用的是laravel框架,里面有用到Job,以队列的方式在执行:

ProductUpdateJob::dispatch($product);

结果任务死活发布不到Redis的List里,对应的Job也没有运行。

后面一步步的跟到Laravel的框架里: vendor/laravel/framework/src/Illuminate/Redis/Connections/Connection.php

public function command($method, array $parameters = [])
{
    var_dump($method, $parameters);
    $start = microtime(true);

    $result = $this->client->{$method}(...$parameters);

    $time = round((microtime(true) - $start) * 1000, 2);

    if (isset($this->events)) {
        $this->event(new CommandExecuted($method, $parameters, $time, $this));
    }

    return $result;
}

输出:

string(4) "eval"
array(3) {
  [0]=>
  string(153) "-- Push the job onto the queue...
redis.call('rpush', KEYS[1], ARGV[1])
-- Push a notification onto the "notify" queue...
redis.call('rpush', KEYS[2], 1)"
  [1]=>
  array(3) {
    [0]=>
    string(14) "queues:default"
    [1]=>
    string(21) "queues:default:notify"
    [2]=>
    string(579) "{"uuid":"5b31adf4-4646-4435-a13e-9940450261da","displayName":"App\\Jobs\\TestJob","job":"Illuminate\\Queue\\CallQueuedHandler@call","maxTries":null,"maxExceptions":null,"backoff":null,"timeout":null,"retryUntil":null,"data":{"commandName":"App\\Jobs\\TestJob","command":"O:16:\"App\\Jobs\\TestJob\":10:{s:3:\"job\";N;s:10:\"connection\";N;s:5:\"queue\";N;s:15:\"chainConnection\";N;s:10:\"chainQueue\";N;s:19:\"chainCatchCallbacks\";N;s:5:\"delay\";N;s:11:\"afterCommit\";N;s:10:\"middleware\";a:0:{}s:7:\"chained\";a:0:{}}"},"id":"H97AvylnadgDi2Vp8eA0ieXiNxrgY8Ok","attempts":0}"
  }
  [2]=>
  int(2)
}

发现里面用的是eval命令执行的rpush。

最后在redis里用命令执行eval,结果发现没有这个权限运行:

eval "redis.call('rpush', KEYS[1], ARGV[1])\nredis.call('rpush', KEYS[2], 1)" "queues:default" "queues:default:notify" 
返回:
"ERR command eval not support for your account"

最后联系阿里的客服,建议我们升级Redis的版本后,问题就好了。

期待ing, Mac Book Pro 16寸原型机曝光

相对当前代的mac book pro, 苹果做了这些改变:

  • ARM构架的引入,这是大家所期待的,随着配套软件的成熟,arm带来的速度和功耗优势非常的棒。
  • Touch bar取消了!!这是一个鸡肋的设计,耗电不说,很多软件都不支持,要你何用?快哉!
  • HDMI和SD卡槽又回来了,这才亲民嘛,能放下身段迎合用户,此子可教也,特别是hdmi,方便了很多,SD卡槽对我们做软件开发的用户来讲可能不大,但对于摄影的来讲,很方便。
  • 最后就是屏蔽的圆角变成了硬件层面的了,之前的总感觉怪怪的。

下面就等上市啦,

更重要的是看价格,我要努力存钱了。。。。

Laravel全局分布式锁的使用

获取锁的代码:vendor/laravel/framework/src/Illuminate/Cache/RedisLock.php

/**
 * Attempt to acquire the lock.
 *
 * @return bool
 */
public function acquire()
{
    if ($this->seconds > 0) {
        return $this->redis->set($this->name, $this->owner, 'EX', $this->seconds, 'NX') == true;
    } else {
        return $this->redis->setnx($this->name, $this->owner) === 1;
    }
}

Redis的set有些特殊:vendor/laravel/framework/src/Illuminate/Redis/Connections/PhpRedisConnection.php

/**
* Set the string value in argument as value of the key.
*
* @param string $key
* @param mixed $value
* @param string|null $expireResolution
* @param int|null $expireTTL
* @param string|null $flag
* @return bool
*/
public function set($key, $value, $expireResolution = null, $expireTTL = null, $flag = null)
{
    return $this->command('set', [
    $key,
    $value,
    $expireResolution ? [$flag, $expireResolution => $expireTTL] : null, ]);
}

如果在获取锁的时候传了时间,调用redis的set的时候,调用的其实是:
$redis->set($key, $value, [‘NX’, ‘EX’ => $expireTTL])
也就是说不存在的时候才设置该key,过期时间为秒。

Redis的Set操作的参数参考:

  • EX second :设置键的过期时间为 second 秒。 SET key value EX second 效果等同于 SETEX key second value 。
  • PX millisecond :设置键的过期时间为 millisecond 毫秒。 SET key value PX millisecond 效果等同于 PSETEX key millisecond value 。
  • NX :只在键不存在时,才对键进行设置操作。 SET key value NX 效果等同于 SETNX key value 。
  • XX :只在键已经存在时,才对键进行设置操作。

锁的常规使用:

// 设置foo锁的超时时间为5,超过这个时间自动释放
$lock = Cache::lock("foo", 5);
if (!$lock->get()) {
    return false;
}

// 业务处理
$lock->release();

return true;

在指定的时间内获取到锁,如果获取不到会抛出异常:

// 设置foo锁的超时时间为5,超过这个时间自动释放
$lock = Cache::lock("foo", 5);
// 需要在2秒内获取到锁,否则会抛出异常
$lock->block(2);
// 业务处理
$lock->release();

 

Laravel实践笔记

Laravel程序的分层

1、Service层:业务的入口,如UserService

2、Repository层:通常和Service层对应,防止Service文件过大,对一些需要跨Model处理的业务,需要在Repository层来实现。

3、Model层:基础层,一些和数据表相关的简单的功能可以放在这里供调用。

对业务操作的归一化处理

每一个业务项(如用户、文章等,不是每一个表),都需要有一个createXXX、updateXXX、deleteXXX三个方法,他们需要写在Repository类中。

对所有业务层的对象的操作,最终都需要通过这3个方法来实现,这样的目的是做到数据修改的统一处理,方便在这里做日志、缓存等处理。

之所以不通过Laravel检测Model的事件来实现,是因为该种方式是针对单表的,不是针对业务的,会显示太麻烦和不合适。

比如增加一个用户createUser,里面涉及了操作多个表(如用户扩展表),这是一个原子操作,不用对扩展表进行事件的监听处理。

Laravel数据库笔记

在Model里调用self::where等操作时,其实是先到了Model类的 __callStatic 方法,再到了 __call 方法,根据情况,再到了Builder文件,也就是:
vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php

大多数的操作都可以去这里面去找。

别的一些常用操作记录

$flight = App\Models\Flight::create(['name' => 'Flight 10']);
$flight->fill(['name' => 'Flight 22']);


Model::find(1, [字段])
ProductModel::where('id', '1')->value('id')
ProductModel::where(['id' => '1'])->value('id')

ProductModel::where(['id' => '1'])->get(['id','name'])->toArray()
ProductModel::where(['id' => '1'])->first(['id','name'])->toarray()

# find in set
whereRaw("FIND_IN_SET(?, accept_type)", [$param['accept_type']])

// 直接取条一条记录
ProductModel::firstWhere("id", 1)
或
ProductModel::firstWhere("id", "=", 1)


// Insert并获取主键
ProductModel::create(['name'=>'sdfsdfds'])->id

ProductSkuPropertyDataModel::updateOrCreate(
    ['sku_id' => $skuId, 'property_id' => $property['id']],
    [
        'product_id' => $productId,
        'sku_id' => $skuId,
        'property_id' => $property['id'],
        'property_value' => $pValue
    ]
);

ProductStyleImageModel::whereIn('origin_hash', [2,3,4])

// insert
$user = User::create([
    'first_name' => 'Taylor',
    'last_name' => 'Otwell',
    'title' => 'Developer',
]);

// var_dump(ProductModel::where(['id' => '1'])->get(['id','name'])->toarray());
// var_dump(ProductModel::create(['name'=>'sdfsdfds'])->id);

// 插入或更新,其实是先select判断再执行
$spiderStatModel = SpiderStatModel::subSite($site['id']);
$spiderStatModel->updateOrCreate($conditions, $data);
// 或者直接:
Model::updateOrCreate($conditions, $array)

//批量更新
App\Models\Flight::where('active', 1)
          ->where('destination', 'San Diego')
          ->update(['delayed' => 1]);

//单条更新
$flight = App\Models\Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();

$styles = DB::table("t_product_style_0 as product_style")
                    ->where([['product_style.product_id', '=', $product->id]])
                    ->limit(1)
                    ->get();


$model = self::from('huddle as huddle')
        ->leftJoin("store as store", "huddle.store_id", "=", "store.id")
        ->join("store_data as store_data", "huddle.store_id", "=", "store_data.store_id")
        ->join("store_site as store_site", "huddle.store_id", "=", "store_site.store_id")
        ->where([
            'huddle.topic_id' => $actId,
            'huddle.status' => self::STATUS,
            'store_data.status' => self::STATUS,
            'store_site.status' => self::STATUS,
            'store_site.site_id' => $siteId,
            'store_data.lang_id' => $langId,
        ])
        ->where('huddle.status', '>', time())
        ->offset($page * $pageSize)
        ->limit($pageSize);

    $ret = $model->get([
            'huddle.id',
            'huddle.store_id',
            'store_data.name',
            'huddle.rebate',
            'huddle.places',
            'huddle.start_time',
            'huddle.end_time',
            'store.is_upto'
        ])
        ->toArray();


// firstOrNew 需要手动调用 save,才会保存到数据库。适合同时需要修改其他属性的场景。
// firstOrCreate 会自动保存到数据库。适合不需要额外修改其他属性的场景。

use Illuminate\Database\Query\Builder as QueryBuilder;

 

Laravel测试用例编写

测试全部
php artisan test –stop-on-failure

只测试Feature
php artisan test –group=feature –stop-on-failure

只测试某一个文件
php74 vendor/bin/phpunit tests/Feature/ServiceProductTest.php

<?php

namespace Tests\Feature;

use App\Common\ServiceRequestParam;
use App\Services\ProductService;
use App\Models\TagLangModel;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\TestCase;

class SearchTest extends TestCase
{
    // 警告!!!!!!
    // 不要用这个啊,用了数据会被清空
    // use RefreshDatabase; 

    // 使用下面这个,完成后会回滚数据
    // use DatabaseTransactions;


    public function testSearch()
    {
        // TagLangModel::create(['tag_id'=>1, 'name'=>'sdfssfsdf', 'type'=>'NORMAL', 'lang'=>'en-US']);
        $tagService = resolve('App\Services\SearchService');
        $req = ServiceRequestParam::make([
            'word' => 'Farfetch',
            'limit' => 5
        ]);
        $ret = $tagService->searchProduct($req);
        $this->assertTrue($ret->isSuccess());
    }


}

 

注意事项

  • 不要用use RefreshDatabase,用了数据会被清空。
  • 可以用use DatabaseTransactions,用了数据会回滚。
  • Feature相当于集成测试,一些关联比较多的功能需要写在这里面,不然调用不了