mongodb 复制集

首先创建3个conf文件

第一个 mongoDB.conf

dbpath = /soft/mongodb4.0/data/db #数据文件存放目录
logpath = /soft/mongodb4.0/logs/mongodb.log #日志文件存放目录
port = 27017 #端口
fork = true #以守护程序的方式启用,即在后台运行
bind_ip=127.0.0.1
replSet=test1 #复制集 统一名称

第二个 mongodb-1.conf

dbpath = /soft/mongodb4.0/data1/db #数据文件存放目录
logpath = /soft/mongodb4.0/logs1/mongodb.log #日志文件存放目录
port = 27018 #端口
fork = true #以守护程序的方式启用,即在后台运行
bind_ip=127.0.0.1 #允许所有的连接
replSet=test1

第三个 mongodb-2.conf

dbpath = /soft/mongodb4.0/data2/db #数据文件存放目录
logpath = /soft/mongodb4.0/logs2/mongodb.log #日志文件存放目录
port = 27019 #端口
fork = true #以守护程序的方式启用,即在后台运行
bind_ip=127.0.0.1 #允许所有的连接
replSet=test1

接着运行第一,2,3 个conf文件

./mongod -f ../mongodb.conf

./mongod -f ../mongodb-1.conf

./mongod -f ../mongodb-2.conf

接着运行 第一台 127.0.0.1:27017 mongo

运行以下代码

rs.initiate({_id:”test2″,members:[{_id:0,host:”127.0.0.1:27017″,”priority”:100},{_id:1,host:”127.0.0.1:27018″,”priority”:90},{_id:2,host:”127.0.0.1:27019″,”priority”:80}] })

返回结果 ok

{
“ok” : 1,
“operationTime” : Timestamp(1556585401, 1),
“$clusterTime” : {
“clusterTime” : Timestamp(1556585401, 1),
“signature” : {
“hash” : BinData(0,”AAAAAAAAAAAAAAAAAAAAAAAAAAA=”),
“keyId” : NumberLong(0)
}
}
}

接着退出 查看 27018 27019 mongodb

就会变成这样 test2:SECONDARY 节点

而27017 就会变成

test2:PRIMARY 主节点

接着

use huxierong

db.huxierong_user.insert({title:”123456″})

退出27017 进入 27018

rs.slaveOk(); 可以在副集中查看读取数据

use huxierong

show collections

就能看到 huxierong_user 这个文档了

然后 db.huxierong_user.find() 就能看到数据了

27019 同样方式查看

android aes加密类

package com.news.huxierong.utils;

import android.util.Base64;
import android.util.Log;

import java.io.UnsupportedEncodingException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;


public class AESHelper {
    /**
     * 算法/模式/填充
     **/
    private static final String CipherMode = "AES/ECB/PKCS5Padding";
    private static final String password = Md5Utils.md5("huxierong");

    /**
     * 创建密钥
     *
     * @param password 例如:"0123456701234567" 128位 16*8 所有密钥长度不能超过16字符中文占两个。192 24;
     *                 256 32
     * @return SecretKeySpec 实例
     */
    private static SecretKeySpec createKey(String password) {
        byte[] data = null;
        if (password == null) {
            password = "";
        }
        StringBuffer sb = new StringBuffer(32);
        sb.append(password);
        while (sb.length() < 32) {
            sb.append("0");
        }
        if (sb.length() > 32) {
            sb.setLength(32);
        }

        try {
            data = sb.toString().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new SecretKeySpec(data, "AES");
    }

    /**
     * 加密字节数据
     *
     * @param content  需要加密的字节数组
     * @param password 密钥 128 <16个字节 192 <24,256 <32个字节
     * @return 加密完后的字节数组
     */
    public static byte[] encrypt(byte[] content, String password) {
        try {
            SecretKeySpec key = createKey(password);
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 加密(结果为16进制字符串)
     *
     * @param content  要加密的字符串
     * @param password 密钥
     * @return 加密后的16进制字符串
     */
    public static String encrypt(String content, String password) {
        byte[] data = null;
        try {
            data = content.getBytes("UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        data = encrypt(data, password);
        String result = Base64.encodeToString(data, Base64.NO_WRAP);
        return result;
    }

    /**
     * 加密(结果为16进制字符串)
     *
     * @param content 要加密的字符串
     * @return 加密后的16进制字符串
     */
    public static String encrypt(String content) {
        byte[] data = null;
        try {
            data = content.getBytes("UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        data = encrypt(data, password);
        String result = Base64.encodeToString(data, Base64.NO_WRAP);
        return result;
    }

    /**
     * 解密字节数组
     **/
    public static byte[] decrypt(byte[] content, String password) {
        try {
            SecretKeySpec key = createKey(password);
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密16进制的字符串为字符串
     **/
    public static String decrypt(String content, String password) {
        byte[] data = null;
        try {
            data = Base64.decode(content, Base64.NO_WRAP);
        } catch (Exception e) {
            e.printStackTrace();
        }
        data = decrypt(data, password);
        if (data == null)
            return null;
        String result = null;
        try {
            result = new String(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 解密16进制的字符串为字符串
     **/
    public static String decrypt(String content) {
        byte[] data = null;
        try {
            data = Base64.decode(content, Base64.NO_WRAP);
        } catch (Exception e) {
            e.printStackTrace();
        }
        data = decrypt(data, password);
        if (data == null)
            return null;
        String result = null;
        try {
            result = new String(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 字节数组转成16进制字符串
     *
     * @param b
     * @return 16进制字符串
     */
    public static String byte2hex(byte[] b) { // 一个字节的数,
        StringBuffer sb = new StringBuffer(b.length * 2);
        String tmp = "";
        for (int n = 0; n < b.length; n++) {
            // 整数转成十六进制表示
            tmp = (Integer.toHexString(b[n] & 0XFF));
            if (tmp.length() == 1) {
                sb.append("0");
            }
            sb.append(tmp);
        }
        return sb.toString().toUpperCase(); // 转成大写
    }

    /**
     * 将hex字符串转换成字节数组 *
     *
     * @param inputString 16进制的字符串
     * @return 字节数组
     */
    private static byte[] hex2byte(String inputString) {
        if (inputString == null || inputString.length() < 2) {
            return new byte[0];
        }
        inputString = inputString.toLowerCase();
        int l = inputString.length() / 2;
        byte[] result = new byte[l];
        for (int i = 0; i < l; ++i) {
            String tmp = inputString.substring(2 * i, 2 * i + 2);
            result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);
        }
        return result;
    }
}

nginx编译 lua

转载 https://www.imooc.com/article/19597 lua模块 
wget http://luajit.org/download/LuaJIT-2.0.2.tar.gz
make install  PREFIX=/usr/local/LuaJIT 
export LUAJIT_LIB=/usr/local/LuaJIT/lib
export LUAJIT_INC=/usr/local/LuaJIT/include/luajit-2.0

wget https://github.com/simpl/ngx_devel_kit/archive/v0.3.0.tar.gz
wget https://github.com/openresty/lua-nginx-module/archive/v0.10.9rc7.tar.gz

git clone https://github.com/arut/nginx-rtmp-module.git

nginx 前置查看 https://blog.csdn.net/sinat_34344123/article/details/79094003

cd /soft/nginx
./configure --prefix=/soft/nginx --with-http_ssl_module --add-module=/downSoft/nginx-rtmp-module --add-module=/downSoft/lua-nginx-module-0.10.9rc7 --add-module=/downSoft/ngx_devel_kit-0.3.0

make make install
echo "/usr/local/LuaJIT/lib" >> /etc/ld.so.conf
然后执行如下命令:
ldconfig

下载 openresty http://openresty.org/cn/linux-packages.html
修改nginx.conf

    http{
    	....
    	lua_package_path "/usr/local/openresty/lualib/?.lua;;"; //添加lua库
    	 server {
	        listen       80;
	        server_name  localhost;
	
	        #charset koi8-r;
	
	        #access_log  logs/host.access.log  main;
	
	        location / {
	            default_type 'text/html';
	            content_by_lua '
	
	                local redis = require "resty.redis"
	                ngx.say("Hello, Lua!")
	            ';
	            content_by_lua_file "/soft/nginx/conf/test.lua";
	            #root   html;
	            #index  index.html index.htm;
	        }
		}
    }

数据库备份 git 上传shell脚本

#!/bin/bash
#

echo `mysqldump --defaults-extra-file=/usr/local/mysql/my.cnf --all-databases > /db/all.sql`
today_date=`date +'%Y%m%d%H%M%S'`
cd /db
echo `git add all.sql`
echo `git commit -m $today_date`
echo `git push -f usdb master`

php单例模式 云片网短信 封装

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/13
 * Time: 15:30
 */

namespace app\common\lib;

use think\Log;

class SendSms
{

    private static $_instance = null;

    private function __construct()
    {

    }

    public static function getInstance()
    {
        if(is_null(self::$_instance))
        {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function send($phone=0)
    {
        if(!$phone)
        {
            throw new ApiException("请输入手机号码!",0,500);
        }

        $code = rand(1000,9999);

        $post_data = array(
            "apikey" => config('app.sms_apikey'),
            "mobile" => $phone,
            "text"=>"【云片网】您的验证码是".$code
        );
        $headers = array(
            'Accept:application/json;charset=utf-8;',
            'Content-Type:application/x-www-form-urlencoded;charset=utf-8;'
        );
        $url = 'https://sms.yunpian.com/v2/sms/single_send.json';
        $postUrl = $url;

        try{

            $ch = curl_init();//初始化curl
            curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
            curl_setopt($ch, CURLOPT_POST, 1);//post提交方式

            curl_setopt($ch, CURLOPT_TIMEOUT, 1);

            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));

            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在

            $data = curl_exec($ch);//运行curl
            curl_close($ch);

            $res = json_decode($data,true);
            if($res)
            {
                if(array_key_exists('http_status_code',$res))
                {
                    if($res['http_status_code']==400)
                    {
                        Log::error(config('static_name.sms_error').$phone." ------ ".$data);
                    }
                }
            }

            return $code;

        }catch (\Exception $e)
        {
            Log::error(config('static_name.sms_error').$phone." ------ ".$e->getMessage());
            return false;
        }

    }
}

/*
 * 使用方法
 */
SendSms::getInstance()->send("1536*****");

lua redis nginx 根据ip来做限制

lua 脚本
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok,err = red:connect("127.0.0.1",6379)

local str = os.time()
local headers = ngx.req.get_headers()
local ip = headers["X-REAL-IP"] or headers["X_FORWARDED_FOR"] or ngx.var.remote_addr

local res = red:lrange(ip,0,-1)
local len = table.getn(res)

if not ip then
        ngx.say("ip地址不能为空!")
        return
end
if len < 30 then
        red:lpush(ip,str)
else
        local start_time = red:lindex(ip,0)
        if str-start_time < 30 then
                ngx.say("频繁访问!")
                return
        else
                ngx.say("重新开始!")
                red:del(ip)
        end
end

保存脚本为 test1.lua

nginx
lua_package_path "/usr/local/openresty/lualib/?.lua;;"; //redis.lua 路径 如果找不到 find / -name redis.lua 找一下

server{
	location / {
                #default_type 'text/plain';
                add_header Content-type 'text/html;charset=utf-8';
                content_by_lua_file conf/test1.lua;
        }
}

shell脚本 查看 mysql nginx php 是否运行

#!/bin/bash
#
#ps -ef | grep -i mysql | grep -v root | awk '{print $2}'
PATH_NAME='/shTest/position/'
FILE_NAME='position.cpy'

#获取配置文件
get_all_group(){
        if [ -e $PATH_NAME$FILE_NAME ]
        then
                GROUP_LIST=`sed -n '/\[GROUP\]/,/\[.*\]/p' $PATH_NAME$FILE_NAME | egrep -v '(^$|\[.*\])'`
                echo "$GROUP_LIST"
        else
                echo "文件不存在!"
        fi
}

#获取配置文件参数里的 pid
get_group_pid()
{
        group_pid=`ps -A | grep -i $1 | awk '{print $1}' | head -1`
        #echo $group_pid
        if [ $group_pid ]
        then
                echo $group_pid
        else
                echo Null
        fi;
}

#获取列表组 参数信息
get_group_list()
{
        echo "NAME"" ----------------- ""PID"" ----------------- ""GROUP"
        for list in `get_all_group`
        do
                #echo "sed -n '/\[$list\]/,/\[.*\]/p' $PATH_NAME$FILE_NAME | egrep -v '(^$|\[.*\])'"
                group_name=`sed -n "/\[$list\]/,/\[.*\]/p" $PATH_NAME$FILE_NAME | egrep -v '(^$|\[.*\])'`
                echo $group_name" ----------------- "`get_group_pid $group_name`" ----------------- "$list
        done
}

get_group_list


position.cpy 文件信息
[GROUP]
WEB
DB
PROGRAMING

[WEB]
NGINX

[DB]
MYSQL

[PROGRAMING]
PHP

mysql存储过程 添加用户和token

BEGIN
DECLARE user_id INT;
DECLARE date_time INT;
start transaction;
    set date_time = (select unix_timestamp());
    INSERT into cartoon_user(username,password,update_time,create_time) VALUES(user_name,pass_word,date_time,date_time);
    set user_id = (select id from cartoon_user where username = user_name);
    INSERT into cartoon_token(user_id,token,ip,update_time,create_time) VALUES(user_id,user_token,token_ip,date_time,date_time);
    select user_id;
commit;
end