drinke9 发布的文章

介绍

在接触Docker之前,一直使用自建的开发环境来工作。

对于个人来说就是在换电脑的时候麻烦,换电脑了开发环境就得重新部署一次。差不得得要个半天时间...

对于公司团队来说更加麻烦了,每个同事部署的环境不一致,Windows系统与*nix系统的不兼容等.代码跑起来有差异。

Docker是一个类似于虚拟机的设计,一种新兴化的虚拟化方式。

特性Docker虚拟机
启动秒级分钟级
硬盘使用一般为MB一般为GB
性能接近原生弱于原生
系统支持量单主机支持上千个容器一般几十个

Docker有三个关键概念:镜像(images)、容器(container)、仓库(registry)。其中镜像与容器两者关系类似于面向对象设计中的实例一样

镜像是静态的定义,容器是镜像运行是的实体

镜像加速:官方Docker Hub拉取镜像网络不稳定,推荐两个镜像仓库


- 阅读剩余部分 -

在使用vee-validate验证表单中受限于默认规则不够用,于是查阅文档,记录下如何自定义验证规则.

格式:

const validator = {
  getMessage(field, args) {
    //定义默认错误提示
    //返回错误提示
  },
  validate(value, args) {
        // 返回一个 Boolean 值或者一个 Promise对象.
  }
};

使用 extend(name,validator)函数添加一个验证实例

Validator.extend('truthy', {
  getMessage: field => 'The ' + field + ' value is not truthy.',
  validate: value => !! value
});

列子:

const myCustomRule = {
  getMessage(field, args) {
      return field + '格式不正确'
  },
  validate(value, args) {
      return value.length == 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/.test(value)
  }
};

Validator.extend('isMobile',myCustomRule);

定义通过后台接口验证的规则:

Validator.extend('sku', {
    getMessage: field => field + '已存在!',
    validate: (value, args) => {
        return this.checkSku(value);
    }
}, {
    immediate: false    //是否实时验证
});

checkSku(val) {
    return this.$api.checkSku(val).then(res => {
        if (res.code == 200) {
            return true;
        } else {
            return false;
        }
    });
},

laravel中使用:

  • app.js中引入文件

    ...
    import VeeValidate, {Validator} from 'vee-validate';
    import zh_CN from '../locale/zh_CN';
    ...
    Validator.localize('zh_CN', zh_CN);
    Vue.use(VeeValidate, {
    locale: 'zh_CN',
    fieldsBagName: 'fieldBags',
    });
    //手机号验证规则(可在所有组件中使用)
    const isMobile = {
        getMessage: field => field + '格式不正确',
        validate: (value, args) => {
            return value.length == 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/.test(value)
        }
    }
    Validator.extend('mobile', isMobile);
  • 在组件中自定义规则

    <template>
      <form>
        <div :class="{'has-error' : errors.has('name')}">
          <input type="text" name="name" v-validate="'myName'">
          <span class="help-block" v-show="errors.has('name')">{{ errors.first('name') }}</span>
        </div>
      </form>
    </template>
    
    <script>
    export default {
            created() {
                this.$validator.extend('myName', {
                    getMessage: field => field + '已存在!',
                    validate: (value, args) => {
                        return this.checkName(value);
                    }
                }, {
                    immediate: false
                });
            },
            methods:{
                checkName(val) {
                    return this.$api.checkName(val).then(res => {
                        return res.code == 200 ? true : false;
                    });
                },
            }
    }
    </script>

设定验证触发条件,默认是change添加以下配置变成失去焦点验证

data-vv-validate-on="blur"

<input type="text" name="name" data-vv-as="姓名" v-validate="'required|chinese'" data-vv-validate-on="blur" v-model="name">

VeeValidate表单验证组件Ajax成功后消除验证错误

methods:{
    clear(){
        let that = this;
        new Promise(function (resolve, reject) {
            resolve('Reset Form!');
            that.clearForm();
        }).then(() => {
            that.$validator.reset();
        });
    },
    clearForm(){
        //do anything...
    }
}

Reference:文档

闲来无事,将闲置VPS搭建一个私有云。

所需配置

  • vps主机一台
  • oneinstack 安装包
  • owncloud 安装包

步骤

  • 安装oneinstack(略)

    1. 安装mysql
    2. 安装PHP
    3. 安装Nginx/Apache (owncloud 默认使用Apache做web服务器、如果使用Nginx需要修改NGINX配置、见下文)
    4. 安装Redis/Memcache(解决内存太小问题、提升访问速度)
  • 安装owncloud

    > 当前最新地址 https://download.owncloud.org/community/owncloud-10.0.9.tar.bz2
    
    #下载owncloud安装包
    $ wget https://download.owncloud.org/community/owncloud-10.0.9.tar.bz2
    #解压文件
    $ tar -jxf owncloud-10.0.9.tar.bz2
    #拷贝文件至/data/wwwroot/
    $ mkdir /data/wwwroot/owncloud && cp -r owncloud/* /data/wwwroot/owncloud/
    #以上有一处坑点!cp命令复制的时候回忽略.开头的文件 .htaccess .usr.ini 这两个文件需要手动移动至目标文件夹
  • 接下来创建对应的数据库和用户(略)
  • 使用./vhost.sh创建虚拟主机(oneinstack)
  • 依据文档修改nginx配置

附上简略nginx配置

server {
  listen 80;
  listen 443 ssl http2;
  ssl_certificate /usr/local/nginx/conf/ssl/fuck.crt;
  ssl_certificate_key /usr/local/nginx/conf/ssl/fuck.key;
  ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
  ssl_ciphers EECDH+CHACHA20:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;
  ssl_prefer_server_ciphers on;
  ssl_session_timeout 10m;
  ssl_session_cache builtin:1000 shared:SSL:10m;
  ssl_buffer_size 1400;
    # add_header Strict-Transport-Security max-age=15768000;
    # Add headers to serve security related headers
    # Before enabling Strict-Transport-Security headers please read into this topic first.
    add_header Strict-Transport-Security "max-age=15552000; includeSubDomains";
    add_header X-Content-Type-Options nosniff;
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Robots-Tag none;
    add_header X-Download-Options noopen;
    add_header X-Permitted-Cross-Domain-Policies none;

    # set max upload size
    #      client_max_body_size 512M;
    #      fastcgi_buffers 8 4K;                     # Please see note 1
    #      fastcgi_ignore_headers X-Accel-Buffering; # Please see note 2
    error_page 403 /core/templates/403.php;
    error_page 404 /core/templates/404.php;
  ssl_stapling on;
  ssl_stapling_verify on;
  server_name fuck.happyhack.cn;
  access_log /data/wwwlogs/fuck.happyhack.cn_nginx.log combined;
  index index.html index.htm index.php;
  root /data/wwwroot/owncloud;
  if ($ssl_protocol = "") { return 301 https://$host$request_uri; }

  include /usr/local/nginx/conf/rewrite/none.conf;
  #error_page 404 /404.html;
  #error_page 502 /502.html;
location / {
    rewrite ^ /index.php$uri;
}

location ~ ^/(?:build|tests|config|lib|3rdparty|templates|data)/ {
    return 404;
}
location ~ ^/(?:\.|autotest|occ|issue|indie|db_|console) {
    return 404;
}


location ~ ^/(?:index|remote|public|cron|core/ajax/update|status|ocs/v[12]|updater/.+|ocs-provider/.+|core/templates/40[34])\.php(?:$|/) {
    fastcgi_split_path_info ^(.+\.php)(/.*)$;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param SCRIPT_NAME $fastcgi_script_name; # necessary for owncloud to detect the contextroot https://github.com/owncloud/core/blob/v10.0.0/lib/private/AppFramework/Http/Request.php#L603
    fastcgi_param PATH_INFO $fastcgi_path_info;
    fastcgi_param HTTPS on;
    fastcgi_param modHeadersAvailable true; #Avoid sending the security headers twice
    fastcgi_param front_controller_active true;
    fastcgi_read_timeout 180; # increase default timeout e.g. for long running carddav/ caldav syncs with 1000+ entries
    fastcgi_pass unix:/dev/shm/php-cgi.sock;
    fastcgi_intercept_errors on;
    fastcgi_request_buffering off; #Available since NGINX 1.7.11
}

location ~ ^/(?:updater|ocs-provider)(?:$|/) {
    try_files $uri $uri/ =404;
    index index.php;
}
  #location ~ [^/]\.php(/|$) {
  #  #fastcgi_pass remote_php_ip:9000;
  #  fastcgi_pass unix:/dev/shm/php-cgi.sock;
  #  fastcgi_index index.php;
  #  include fastcgi.conf;
  #}

location ~ ^/(?:updater|ocs-provider)(?:$|/) {
    try_files $uri $uri/ =404;
    index index.php;
}
location ~ \.(?:svg|gif|png|html|ttf|woff|ico|jpg|jpeg|map)$ {
    add_header Cache-Control "public, max-age=7200";
    try_files $uri /index.php$uri$is_args$args;
    # Optional: Don't log access to other assets
    access_log off;
}
location ~ \.(?:css|js)$ {
    try_files $uri /index.php$uri$is_args$args;
    add_header Cache-Control "max-age=15778463";
    # Add headers to serve security related headers (It is intended to have those duplicated to the ones above)
    # Before enabling Strict-Transport-Security headers please read into this topic first.
    #add_header Strict-Transport-Security "max-age=15552000; includeSubDomains";
    add_header X-Content-Type-Options nosniff;
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Robots-Tag none;
    add_header X-Download-Options noopen;
    add_header X-Permitted-Cross-Domain-Policies none;
    expires 7d;
    # Optional: Don't log access to assets
    access_log off;
}
  location ~ /\.ht {
    deny all;
  }
}
  • 重启nginx

访问web安装界面

创建管理员用户、选择使用mysql为数据库。大功告成!

优化

使用crontab定时命令来代替Ajax执行脚本

#查看php所在路径
$ which php
/usr/local/php/bin/php
# 使用www用户添加定时任务 (可能会让你选择使用什么编辑器、当然是vim啦!)
$ sudo crontab -u www -e
# 添加以下代码 30分钟执行一次任务
30  *  *  *  * /usr/local/php/bin/php -f /data/wwwroot/owncloud/cron.php

客户端安装

  • Mac

    >https://download.owncloud.com/desktop/stable/ownCloud-qt5.6.2-2.4.2.10200.pkg
    
  • Andriod

    通过GooglePay需要$0.9、良心作者给了一个第三方下载APK[地址](https://f-droid.org/packages/com.owncloud.android/)
    

Laravel 框架中对 Mysql 查询复查语句的时候,有时候会遇到sql在MySQL终端中运行没问题,但是在laravel中出现错误.

  • 举个

查询表中name有重复的数据

$sql = " `name` IN (SELECT `name` FROM clients child GROUP BY child.`name` HAVING COUNT(child.`name`) > 1 ) ORDER BY `name`";

$clients = Client::whereRaw($sql)->paginate();

通过toSql()将sql打出来放到mysql终端中执行是没有问题的,但是在laravel框架中则会出现:

Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause

  • 解决办法

config/database.php中mysql的 strict改为false就可以啦!

MongoDB 权限配置

MongoDB 默认没有管理员账号,如果需要开启权限必须先添加管理员账号。

  • 切换到 admin (Collection-集合)
> use admin
switched to db admin
> show collections
system.version
  • 创建超级管理员用户
> db.createUser({user:'root',pwd:'root',roles:["root"]})
Successfully added user: { "user" : "root", "roles" : [ "root" ] }
> show users
{
    "_id" : "admin.root",
    "user" : "root",
    "db" : "admin",
    "roles" : [
        {
            "role" : "root",
            "db" : "admin"
        }
    ]
}
##  官方例子
use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: "abc123",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)
## 官方例子
use reporting
db.createUser(
  {
    user: "reportsUser",
    pwd: "12345678",
    roles: [
       { role: "read", db: "reporting" },
       { role: "read", db: "products" },
       { role: "read", db: "sales" },
       { role: "readWrite", db: "accounts" }
    ]
  }
)
  • 切到所在集合,创建用户
>use mycollections
>db.createUser(
  {
    user: "reportsUser",
    pwd: "12345678",
    roles: [
       { role: "read", db: "reporting" },
       { role: "read", db: "products" },
       { role: "read", db: "sales" },
       { role: "readWrite", db: "accounts" }
    ]
  }
)

MongoDB 开启Auth认证

修改配置文件mongod.conf

security:
  authorization: enabled
  #authorization: disabled

## 网络上很多资料是以下配置,
auth=true

Enable Access Control

MongoDB does not enable access control by default. You can enable authorization using the --auth or the security.authorization setting. Enabling internal authentication also enables client authorization.

官方配置文档

Laravel中使用MongoDB

安装扩展包composer require jenssegers/mongodb.
修改config/database.php配置文件

'mongodb' => [
       'driver'   => 'mongodb',
       'host'     => env('MONGO_DB_HOST', 'localhost'),
       'port'     => env('MONGO_DB_PORT', 27017),
       'database' => env('MONGO_DB_DATABASE'),
       'username' => env('MONGO_DB_USERNAME'),
       'password' => env('MONGO_DB_PASSWORD'),
       'options'  => [
           'database' => env('MONGO_DB_DATABASE') // sets the authentication database required by mongo 3
      ]
],

MongoDB是强类型语言,PHP中对MongoDB操作时要注意类型问题!

以下两个查询会得到不一样的结果:

> db.users.find({user_id:1})
> db.users.find({user_id:"1"})

Reference

  1. https://blog.csdn.net/kk185800961/article/details/45619863
  2. https://www.jianshu.com/p/f5afc6488f9e
  3. https://docs.mongodb.com/manual/core/authorization/