作者归档:myjoyoo

CentOS安装多PHP环境

yum install epel-release
yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpm
yum install yum-utils
yum install -y php73-php-fpm php73-php-cli php73-php-bcmath php73-php-gd php73-php-json php73-php-mbstring php73-php-mcrypt php73-php-mysqlnd php73-php-opcache php73-php-pdo php73-php-pecl-crypto php73-php-pecl-mcrypt php73-php-pecl-geoip php73-php-recode php73-php-snmp php73-php-soap php73-php-xmll
systemctl enable php73-php-fpm
systemctl start php73-php-fpm

安装的配置文件路径:
/etc/opt/remi/php73/

安装路径:
/opt/remi/php83/root/usr/

启动fpm服务
systemctl restart php80-php-fpm

设置为自动运行
chkconfig php80-php-fpm on

CentOS升级curl
rpm -ivh http://www.city-fan.org/ftp/contrib/yum-repo/rhel7/x86_64/city-fan.org-release-2-1.rhel7.noarch.rpm

yum update curl –enablerepo=city-fan.org -y

 

PHP里用SoapClient出现”Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL”处理

在一台很老的服务器上,调用bing的接口时,出现如下错误,以前都是好好的:

PHP Fatal error:  Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://adinsight.api.bingads.microsoft.com/Api/Advertiser/AdInsight/v13/AdInsightService.svc?singleWsdl' : failed to load external entity "https://adinsight.api.bingads.microsoft.com/Api/Advertiser/AdInsight/v13/AdInsightService.svc?singleWsdl"

后面发现Curl也不行,报:Peer certificate cannot be authenticated with known CA certificates 错误。

wget也不行,也报:ERROR: cannot verify certificate。

现在看来是由于系统的根证书无效了(系统太老应该是很多年前的机器了),所以无法判断microsoft的证书的有效性,按如下操作就可以了:

cd /etc/pki/tls/certs
wget https://curl.haxx.se/ca/cacert.pem
cat cacert.pem >> ca-bundle.crt

思路是去下载一个新的可信证书串(上面是curl的,也可以找一个其它的),把这个串放到系统的可信证书后面去。

如果是在php程序里用curl的话,不用设置操作系统的,可以试试把 https://curl.haxx.se/ca/cacert.pem 下载下来后,再设置php.ini的curl设置

[curl]
curl.cainfo=/path/to/downloaded/cacert.pem

 

通过smtp向google gmail发送邮件报错问题处理

在Laravel里用smtp方式通过gmail发送邮件出现下面的错误:

Failed to authenticate on SMTP server with username "[email protected]" using 3 possible authenticators. Authenticator LOGIN returned Expected response code 235 but got code "535", with message "535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/?p=BadCredentials a25sm9780898pfo.27 - gsmtp
". Authenticator PLAIN returned Expected response code 235 but got code "535", with message "535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/?p=BadCredentials a25sm9780898pfo.27 - gsmtp
". Authenticator XOAUTH2 returned Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/?p=BadCredentials a25sm9780898pfo.27 - gsmtp
".

需要按下面的步骤去解决:

1、开启2步验证方式,通过这里:https://www.google.com/landing/2step/

2、为GMAIL设置一个单独的密码,通过这里:https://security.google.com/settings/security/apppasswords

3、把第二步里的密码设置到Laravel的.env文件里。

对于.env邮件的设置也要注意加密方式,下面的我的配置:

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=独立密码
MAIL_ENCRYPTION=tls
[email protected]
MAIL_FROM_NAME="${APP_NAME}"

 

Laravel操作Redis笔记

Laravel操作Redis好麻烦的,也不封闭完。。。

操作Sortd Set

// 判断是否存在
if (Redis::command("exists", [self::REDIS_KEY_MERCHANT_TITLE])) {
    return;
}
// 增加
Redis::zadd(self::REDIS_KEY_MERCHANT_TITLE, 1, "sdfsdf");
// 加分
Redis::command('zIncrBy', [self::REDIS_KEY_MERCHANT_TITLE, 1, "sdfsdf"]);
// 弹出最小的
Redis::command('zPopMin', [self::REDIS_KEY_PROMOTION_DESC, 1]);
// 弹出最大的
Redis::command('zPopMax', [self::REDIS_KEY_PROMOTION_DESC, 1]);

 

Git记录

删除本地分支
git branch -D test –没合并也删除
git branch -d test — 没合并删除不了

删除远程分支
git push origin :feature/ttkh

查看本地分支:git branch
查看远程分支:git branch -r
查看所有分支:git branch -a

切换远程分支:git checkout -b myRelease origin/Release

git remote add origin https://github.com/wu347771769/learngit.git

把某历史版本打出分支
git checkout -b xxx/xxx 5f4648474fb38c75b69dce0db9c4d4ec1b1e6b74

合并到master分支:
git checkout master
git merge issue1234

把本地分支推送到远程分支
新建远程分支前端 CSS.md
git push origin hotfix/liyan-190905:hotfix/liyan-190905

远程已有remote_branch分支但未关联本地分支local_branch且本地已经切换到local_branch
git push -u origin/remote_branch

远程已有remote_branch分支并且已经关联本地分支local_branch且本地已经切换到local_branch
git push

处理更新不下来,分支冲突的情况
[www@xxx]$ git pull
error: ‘refs/remotes/origin/hotfix’ exists; cannot create ‘refs/remotes/origin/hotfix/business-button’
From gitlab.xxxx.com:Project/backend/gocashback-api
! [new branch] hotfix/business-button -> origin/hotfix/business-button (unable to update local ref)
error: some local refs could not be updated; try running
‘git remote prune origin’ to remove any old, conflicting branches
[www@xxxt]$ git remote prune origin
Pruning origin

指定本地分支和远程某个分支的关系
git branch –set-upstream-to=origin/branch_remote branch_local
查看本地的分支是和哪个远程分支关联的
git branch -vv

提交错误后,回滚
https://blog.csdn.net/BigData_Mining/article/details/88179370

使用阿里云的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;