Java生成GBK所有字符,以及判断字符是否是GBK编码内字符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/**
* 参见文档: <a href="https://zh.wikipedia.org/wiki/%E6%B1%89%E5%AD%97%E5%86%85%E7%A0%81%E6%89%A9%E5%B1%95%E8%A7%84%E8%8C%83">汉字内码扩展规范</a>
* <p>
* GBK/1:GB2312非汉字符号: A1~A9, A1~FE
* GBK/2:GB2312汉字: B0~F7, A1~FE
* GBK/3:扩充汉字: 81~A0, 40~FE (7F除外)
* GBK/4:扩充汉字: AA~FE, 40~A0 (7F除外)
* GBK/5:扩充非汉字: A8~A9, 40~A0 (7F除外)
*
* @author Gao Youbo
* @since 2022-08-23 16:34
*/
public class GBK {
private static final Charset CHARSET = Charset.forName("GBK");

/**
* 获取所有GBK编码字符
*/
public static List<String> getGBK() {
List<String> words = new ArrayList<>();
byte[] bytes = new byte[2];

// GBK/1:GB2312非汉字符号
for (int b1 = 0xA1; b1 <= 0xA9; b1++) {
bytes[0] = (byte) b1;
for (int b2 = 0xA1; b2 <= 0xFE; b2++) {
bytes[1] = (byte) b2;
words.add(new String(bytes, CHARSET));
}
}

// GBK/2:GB2312汉字
for (int b1 = 0xB0; b1 <= 0xF7; b1++) {
bytes[0] = (byte) b1;
for (int b2 = 0xA1; b2 <= 0xFE; b2++) {
bytes[1] = (byte) b2;
words.add(new String(bytes, CHARSET));
}
}

// GBK/3:扩充汉字
for (int b1 = 0x81; b1 <= 0xA0; b1++) {
bytes[0] = (byte) b1;
for (int b2 = 0x40; b2 <= 0xFE; b2++) {
bytes[1] = (byte) b2;
if (b2 != 0x7F) {
words.add(new String(bytes, CHARSET));
}
}
}

// GBK/4:扩充汉字
for (int b1 = 0xAA; b1 <= 0xFE; b1++) {
bytes[0] = (byte) b1;
for (int b2 = 0x40; b2 <= 0xA0; b2++) {
bytes[1] = (byte) b2;
if (b2 != 0x7F) {
words.add(new String(bytes, CHARSET));
}
}
}

// GBK/5:扩充非汉字
for (int b1 = 0xA8; b1 <= 0xA9; b1++) {
bytes[0] = (byte) b1;
for (int b2 = 0x40; b2 <= 0xA0; b2++) {
bytes[1] = (byte) b2;
if (b2 != 0x7F) {
words.add(new String(bytes, CHARSET));
}
}
}

return words;
}

public static boolean isGBK(String str) {
boolean isGBK = false;
char[] chars = str.toCharArray();
for (char c : chars) {
byte[] bytes = String.valueOf(c).getBytes(CHARSET);
if (bytes.length == 2) { // GBK 编码为两个字节
int b1 = bytes[0] & 0xff;
int b2 = bytes[1] & 0xff;
if (b1 >= 0xA1 && b1 <= 0xA9 && b2 >= 0xA1 & b2 <= 0xFE) {
isGBK = true;
break;
}

if (b1 >= 0xB0 && b1 <= 0xF7 && b2 >= 0xA1 & b2 <= 0xFE) {
isGBK = true;
break;
}

if (b1 >= 0x81 && b1 <= 0xA0 && b2 >= 0x40 & b2 <= 0xFE && b2 != 0x7F) {
isGBK = true;
break;
}

if (b1 >= 0xAA && b1 <= 0xFE && b2 >= 0x40 & b2 <= 0xA0 && b2 != 0x7F) {
isGBK = true;
break;
}

if (b1 >= 0xA8 && b1 <= 0xA9 && b2 >= 0x40 & b2 <= 0xA0 && b2 != 0x7F) {
isGBK = true;
break;
}
}
}
return isGBK;
}
}

Alfred 使用iTerm

ADD:我在网上找到了一篇更完整的文章,文章中详细介绍了,这么配合使用alfred + iTerm2 + ssh config快速连接远程服务器:https://juejin.cn/post/6844903909916426248

Alfred执行命令时默认使用的是MaxOS系统自带的Terminal,而我平时使用的都是iTerm。在Github上找到了解决方案:https://github.com/vitorgalvao/custom-alfred-iterm-scripts

设置方式直接截图说明:

WechatIMG62.png

配置内容如下(这个内容是我从上面那个Github项目中Copy出来的,可以自行去项目中Copy最新的):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
-- For the latest version:
-- https://github.com/vitorgalvao/custom-alfred-iterm-scripts

-- Set this property to true to always open in a new window
property open_in_new_window : false

-- Set this property to false to reuse current tab
property open_in_new_tab : true

-- Handlers
on new_window()
tell application "iTerm" to create window with default profile
end new_window

on new_tab()
tell application "iTerm" to tell the first window to create tab with default profile
end new_tab

on call_forward()
tell application "iTerm" to activate
end call_forward

on is_running()
application "iTerm" is running
end is_running

on has_windows()
if not is_running() then return false

tell application "iTerm"
if windows is {} then return false
if tabs of current window is {} then return false
if sessions of current tab of current window is {} then return false

set session_text to contents of current session of current tab of current window
if words of session_text is {} then return false
end tell

true
end has_windows

on send_text(custom_text)
tell application "iTerm" to tell the first window to tell current session to write text custom_text
end send_text

-- Main
on alfred_script(query)
if has_windows() then
if open_in_new_window then
new_window()
else if open_in_new_tab then
new_tab()
else
-- Reuse current tab
end if
else
-- If iTerm is not running and we tell it to create a new window, we get two
-- One from opening the application, and the other from the command
if is_running() then
new_window()
else
call_forward()
end if
end if

-- Make sure a window exists before we continue, or the write may fail
repeat until has_windows()
delay 0.01
end repeat

send_text(query)
call_forward()
end alfred_script

这也备份一下修改之前的配置,防止丢失:

1
2
3
4
5
6
on alfred_script(q)
tell application "Terminal"
activate
do script q
end tell
end alfred_script

使用PM2运行springboot项目

新建文件:pm2.json

1
2
3
4
5
6
7
8
9
10
11
12
13
{
"name": "test",
"script": "java",
"args": [
"-jar",
"/home/test/test.jar",
"--spring.profiles.active=prod"
],
"exec_interpreter": "",
"exec_mode": "fork",
"error_file" : "/data/logs/error.log",
"out_file" : "/data/logs/out.log"
}

然后执行命令:pm2 start pm2.json启动服务。

同时安装多个版本JDK,快速切换JDK版本

推荐一个工具:https://github.com/jenv/jenv

1. Getting Started

Follow the steps below to get a working jenv installation with knowledge of your java environment. Read all the code you execute carefully: a $ symbol at the beginning of a line should be omitted, since it’s meant to show you entering a command into your terminal and observing the response after the command.

1.1 Installing jenv

On OSX, the simpler way to install jEnv is using Homebrew

position-relative
1
brew install jenv

Alternatively, and on Linux, you can install it from source :

position-relative
1
2
3
4
5
6
7
git clone https://github.com/jenv/jenv.git ~/.jenv
# Shell: bash
echo 'export PATH="$HOME/.jenv/bin:$PATH"' >> ~/.bash_profile
echo 'eval "$(jenv init -)"' >> ~/.bash_profile
# Shell: zsh
echo 'export PATH="$HOME/.jenv/bin:$PATH"' >> ~/.zshrc
echo 'eval "$(jenv init -)"' >> ~/.zshrc

Restart your shell by closing and reopening your terminal window or running exec $SHELL -l in the current session for the changes to take effect.

To verify jenv was installed, run jenv doctor. On a macOS machine, you’ll observe the following output:

position-relative
1
2
3
4
5
6
$ jenv doctor
[OK] No JAVA_HOME set
[ERROR] Java binary in path is not in the jenv shims.
[ERROR] Please check your path, or try using /path/to/java/home is not a valid path to java installation.
PATH : /Users/user/.jenv/libexec:/Users/user/.jenv/shims:/Users/user/.jenv/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
[OK] Jenv is correctly loaded

Observe that jenv is correctly loaded but Java is not yet installed.

To make sure JAVA_HOME is set, make sure to enable the export plugin:

position-relative
1
2
jenv enable-plugin export
exec $SHELL -l

Problem? Please visit the Trouble Shooting Wiki page.

Continue to the next section to install java.

Untested: While this fork has improved fish shell support, it has not been tested by this maintainer. To install jenv for Fish according to the contributor’s instructions:

position-relative
1
2
3
4
echo 'set PATH $HOME/.jenv/bin $PATH' >> ~/.config/fish/config.fish
echo 'status --is-interactive; and source (jenv init -|psub)' >> ~/.config/fish/config.fish
cp ~/.jenv/fish/jenv.fish ~/.config/fish/functions/jenv.fish
cp ~/.jenv/fish/export.fish ~/.config/fish/functions/export.fish

1.2 Adding Your Java Environment

Use jenv add to inform jenv where your Java environment is located. jenv does not, by itself, install Java.

For example, on macOS, use brew to install the latest Java (OpenJDK 11) followed by the appropriate jenv add PATH_TO_JVM_HOME command to recognize it.

position-relative
1
2
brew install --cask java
jenv add $(/usr/libexec/java_home)

With macOS OpenJDK 11.0.2 installed, for example, either of these commands will add /Library/Java/JavaVirtualMachines/openjdk-11.0.2.jdk/Contents/Home as a valid JVM. Your JVM directory may vary!

Observe now that this version of Java is added to your java versions command:

position-relative
1
2
3
4
5
$ jenv versions
* system (set by /Users/user/.jenv/version)
11.0
11.0.2
openjdk64-11.0.2

By default, the latest version of Java is your system Java on macOS.

We’ll now set a jenv local VERSION local Java version for the current working directory. This will create a .java-version file we can check into Git for our projects, and jenv will load it correctly when a shell is started from this directory.

position-relative
1
2
3
4
$ jenv local 11.0.2
$ exec $SHELL -l
$ cat .java-version
11.0.2

Is JAVA_HOME set?

position-relative
1
2
$ echo ${JAVA_HOME}
/Users/bberman/.jenv/versions/11.0.2

Yes! Observe that JAVA_HOME is set to a valid shim directory. Unlike the main repository’s documentation we helpfully installed the export plugin, and we now have the most important jenv features covered.

If you executed this commands inside your $HOME directory, you can now delete .java-version:

position-relative
1
rm .java-version

1.3 Setting a Global Java Version

Use jenv global VERSION to set a global Java version:

position-relative
1
jenv global 11.0.2

When you next open a shell or terminal window, this version of Java will be the default.

On macOS, this sets JAVA_HOME for GUI applications on macOS using jenv macos-javahome. Integrates this tutorial to create a file that does not update dynamically depending on what local or shell version of Java is set, only global.

1.4 Setting a Shell Java Version

Use jenv shell VERSION to set the Java used in this particular shell session:

position-relative
1
jenv shell 11.0.2

2 Common Workflows

These common workflows demonstrate how to use jenv to solve common problems.

2.1 Using Two JVMs on macOS

Our goal is to have both the latest version of Java and JDK 8 installed at the same time. This is helpful for developing Android applications, whose build tools are sensitive to using an exact Java version.

We’ll resume where we left off with Java 11.0.2 installed. Let’s install Java 8 now:

position-relative
1
2
brew install --cask adoptopenjdk8
brew install --cask caskroom/versions/adoptopenjdk8

This will install the latest version of Java 8 to a special directory in macOS. Let’s see which directory that is:

position-relative
1
2
3
$ ls -1 /Library/Java/JavaVirtualMachines 
adoptopenjdk-8.jdk
openjdk-11.0.2.jdk

Observe the adoptopenjdk-8.jdk directory. Your exact version may vary. We cannot retrieve this using /usr/libexec/java_home, unfortunately. We’ll add the Java home directory using jenv so that it shows up in our jenv versions command:

position-relative
1
2
3
4
5
6
7
8
9
10
11
12
13
$ jenv add /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/
openjdk64-1.8.0.222 added
1.8.0.222 added
1.8 added
$ jenv versions
* system
1.8
1.8.0.222
openjdk64-1.8.0.222
11.0
11.0.2
openjdk64-11.0.2
oracle64-1.8.0.202-ea

MacOS安装PHP

偶然的机会需要用一下PHP,记录下安装方式。本身mac系统是自带php的,但是自带的修改起来及其不方便,不好安装扩展。所以直接使用brew安装。

brew安装php

1
2
3
4
brew search php  使用此命令搜索可用的PHP版本
brew install php@7.3.21 使用此命令安装指定版本的php
brew install brew-php-switcher 安装php多版本切换工具
brew-php-switcher 7.3.21 切换PHP版本到7.3.21(需要brew安装多个版本)

安装PHP扩展

1
2
3
4
5
pecl version 查看版本信息
pecl help 可以查看命令帮助
pecl search redis 搜索可以安装的扩展信息
pecl install redis 安装扩展
pecl install http://pecl.php.net/get/redis-4.2.0.tgz 安装指定版本扩展

在命令行中压缩图片

今天有需求将一些非常大的图片压缩一下,本来想自己写代码进行压缩的,但是觉得这是一个非常常见的需求,应该有现成的解决方案,于是Google了一下,找到了这两个工具:jpegoptim、optipng

安装

我是在MacOS中安装的,Linux上应该也有这个两个工具,请自行摸索

我使用的是brew进行安装,命令如下:

1
2
brew install jpegoptim
brew install optipng

jpegoptim 使用

1
2
3
4
5
6
7
8
# 压缩
jpegoptim file.jpg

# 指定大小压缩
jpegoptim --size=1024k file.jpg

# 移除Exif信息
jpegoptim --strip-exif file.jpg

optipng 使用

1
optipng file.png

xxx is not in the sudoers file解决方法

用sudo时提示”xxx is not in the sudoers file. This incident will be reported.其中XXX是你的用户名,也就是你的用户名没有权限使用sudo,我们只要修改一下/etc/sudoers文件就行了。下面是修改方法:

  1. 进入超级用户模式。也就是输入”su -“,系统会让你输入超级用户密码,输入密码后就进入了超级用户模式。(当然,你也可以直接用root用)
  2. 添加文件的写权限。也就是输入命令chmod u+w /etc/sudoers
  3. 编辑/etc/sudoers文件。也就是输入命令vim /etc/sudoers,输入”i”进入编辑模式,找到这一 行:root ALL=(ALL) ALL在起下面添加xxx ALL=(ALL) ALL(这里的xxx是你的用户名),然后保存(就是先按一 下Esc键,然后输入”:wq”)退出。
  4. 撤销文件的写权限。也就是输入命令chmod u-w /etc/sudoers

HexoClient1.3.0版本发布

更新内容

  • 修复阿里云oss图片上传后url不正确的问题。#60
  • 支持一键调用hexo generate -d命令发布文章,thanks EVINK
    image.png

功能预览

image.png
image.png

相关链接

Golang并发编程

Go语言的并发是基于 goroutine 的,goroutine 类似于线程,但并非线程。可以将 goroutine 理解为一种虚拟线程。Go语言运行时会参与调度 goroutine,并将 goroutine 合理地分配到每个 CPU 中,最大限度地使用CPU性能。

Go 程序从 main 包的 main() 函数开始,在程序启动时,Go 程序就会为 main() 函数创建一个默认的 goroutine。

下面我们来看一个例子,在线演示:https://play.golang.org/p/U9U-qjuY0t1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package main

import (
"fmt"
"time"
)

func main() {
// 创建一个goroutine
go runing()
// 创建一个匿名的goroutine
go func() {
fmt.Println("喜特:" + time.Now().String())
}()

// 这里sleep一下是因为main方法如果执行完了,main该程序创建的所有goroutine都会退出
time.Sleep(5 * time.Second)
}

func runing() {
fmt.Println("法克:" + time.Now().String())
time.Sleep(3 * time.Second)
}

输出:
法克:2009-11-10 23:00:00 +0000 UTC m=+0.000000001
喜特:2009-11-10 23:00:00 +0000 UTC m=+0.000000001

执行结果说明fuck函数中的sleep三秒并没有影响喜特的输出。

如果说 goroutine 是Go语言程序的并发体的话,那么 channel 就是它们之间的通信机制。一个 channel 是一个通信机制,它可以让一个 goroutine 通过它给另一个 goroutine 发送值信息。每个 channel 都有一个特殊的类型,也就是 channel 可发送数据的类型。一个可以发送 int 类型数据的 channel 一般写为 chan int。

下面我们利用goroutine+channel来实现一个生产消费者模型,示例代码如下,在线执行:https://play.golang.org/p/lqUBugLdU-I

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package main

import (
"fmt"
"time"
)

func main() {
// 创建一个通道
channel := make(chan int64)

// 异步去生产
go producer(channel)

// 数据消费
consumer(channel)
}

// 生产者
func producer(channel chan<- int64) {
for {
// 将数据写入通道
channel <- time.Now().Unix()
// 睡1秒钟
time.Sleep(time.Second)
}
}

// 消费者
func consumer(channel <-chan int64) {
for {
timestamp := <-channel
fmt.Println(timestamp)
}
}

输出为如下:(每秒钟打印一次)
1257894000
1257894001
1257894002
1257894003

Golang指针类型和值类型

Java中值类型和引用类型都是定死的,int、double、float、long、byte、short、char、boolean为值类型,其他的都是引用类型,而Go语言中却不是这样。

在Go语言中:

  • &表示取地址,例如你有一个变量a那么&a就是变量a在内存中的地址,对于Golang指针也是有类型的,比如a是一个string那么&a是一个string的指针类型,在Go里面叫&string。
  • *表示取值,接上面的例子,假设你定义b := &a 如果你打印b,那么输出的是&a的内存地址,如果要取值,那么需要使用:*b

下面我们来看下例子,在线运行:https://play.golang.org/p/jxAKyVMjnoy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package main

import (
"fmt"
)

func main() {
a := "123"
b := &a

fmt.Println(a)
fmt.Println(b)
fmt.Println(*b)
}

输出结果为:
123
0x40c128
123

Java程序员Go语言入门简介

为什么是Go语言

  • 类C的语法,这意味着Java、C#、JavaScript程序员能很快的上手
  • 有自己的垃圾回收机制
  • 跨平台、编译即可执行无需安装依赖环境
  • 支持反射

Go语言简介

Go 语言(或 Golang)起源于 2007 年,并在 2009 年正式对外发布。Go 是非常年轻的一门语言,它的主要目标是“兼具Python等动态语言的开发速度和 C/C++ 等编译型语言的性能与安全性”。

数据类型

数据类型 说明
bool 布尔
string 字符串
int uint8,uint16,uint32,uint64,int8,int16,int32,int64
float float32,float64
byte byte

参考:https://www.runoob.com/go/go-data-types.html

基本语法

HelloWorld

在线运行示例:https://play.golang.org/p/-4RylAqUV36

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import "fmt"

var name string

func init() {
name = "world"
}

func main() {
fmt.Println("hello " + name)
}

我们来执行一下:

1
2
$ go run main.go # main.go 为刚刚创建的那个文件的名称
$ hello world

变量

变量声明

在线运行示例:https://play.golang.org/p/zPqCkRZgrgp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main

import (
"fmt"
)

func main() {
var name string // 声明
name = "gaoyoubo" // 赋值
fmt.Println(name)

var age int = 18 // 声明并赋值
fmt.Println(age)
}

类型推断

在线运行示例:https://play.golang.org/p/0My8veBvtJ8

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import (
"fmt"
)

func main() {
name := "gaoyoubo"
fmt.Println(name)

age := 18
fmt.Println(age)
}

函数

  • 函数可以有多个返回值
  • 隐式的指定函数是private还是public,函数首字母大写的为public、小写的为private
  • 没有类似Java中的try cachethrow,Go语言是通过将error作为返回值来处理异常。
  • 不支持重载

下面我们通过一个示例来了解一下,在线运行示例:https://play.golang.org/p/PYy3ueuPFS6

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package main

import (
"errors"
"fmt"
"strconv"
)

func main() {
log1()

log2("hello world")

ret1 := add1(1, 1)
fmt.Println("add1 result:" + strconv.Itoa(ret1))

ret2, err := Add2(0, 1)
if err == nil {
fmt.Println("Add2 result:" + strconv.Itoa(ret2))
} else {
fmt.Println("Add2 error", err)
}
}

// 私有、无入参、无返回值
func log1() {
fmt.Println("execute func log1")
}

// 私有、入参、无返回值
func log2(msg string) {
fmt.Println("execute func log2:" + msg)
}

// 私有、两个入参、一个返回值
func add1(count1, count2 int) int {
total := count1 + count2
fmt.Println("execute func add3, result=" + strconv.Itoa(total))
return total
}

// Public、两个入参、多个返回值
func Add2(count1, count2 int) (int, error) {
if count1 < 1 || count2 < 1 {
return 0, errors.New("数量不能小于1")
}
total := count1 + count2
return total, nil
}

该示例输出结果为:

1
2
3
4
5
execute func log1
execute func log2:hello world
execute func add3, result=2
add1 result:2
Add2 error 数量不能小于1

但函数有多个返回值的时候,有时你只关注其中一个返回值,这种情况下你可以将其他的返回值赋值给空白符:_,如下:

1
2
3
4
_, err := Add2(1, 2)
if err != nil {
fmt.Println(err)
}

空白符特殊在于实际上返回值并没有赋值,所以你可以随意将不同类型的值赋值给他,而不会由于类型不同而报错。

结构体

Go语言不是像Java那样的面向对象的语言,他没有对象和继承的概念。也没有class的概念。在Go语言中有个概念叫做结构体(struct),结构体和Java中的class比较类似。下面我们定义一个结构体:

1
2
3
4
5
type User struct {
Name string
Gender string
Age int
}

上面我们定义了一个结构体User,并为该结构体分别设置了三个公有属性:Name/Gender/Age,下面我们来创建一个User对象。

1
2
3
4
5
user := User{
Name: "hahaha",
Gender: "男",
Age: 18, // 值得一提的是,最后的逗号是必须的,否则编译器会报错,这就是go的设计哲学之一,要求强一致性。
}

结构体的属性可以在结构体内直接声明,那么如何为结构体声明函数(即Java中的方法)呢,我们来看下下面的示例:在线运行示例:https://play.golang.org/p/01_cTu0RzdH

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main

import "fmt"

type User struct {
Name string
Gender string
Age int
}

// 定义User的成员方法
func (u *User) addAge() {
u.Age = u.Age + 1
}

func main() {
user := User{
Name: "哈", // 名称
Gender: "男", // 性别
Age: 18, // 值得一提的是,最后的逗号是必须的,否则编译器会报错,这就是go的设计哲学之一,要求强一致性。
}
user.addAge()
fmt.Println(user.Age)
}

指针类型和值类型

Java中值类型和引用类型都是定死的,int、double、float、long、byte、short、char、boolean为值类型,其他的都是引用类型,而Go语言中却不是这样。

在Go语言中:

  • &表示取地址,例如你有一个变量a那么&a就是变量a在内存中的地址,对于Golang指针也是有类型的,比如a是一个string那么&a是一个string的指针类型,在Go里面叫&string。
  • *表示取值,接上面的例子,假设你定义b := &a 如果你打印b,那么输出的是&a的内存地址,如果要取值,那么需要使用:*b

下面我们来看下例子,在线运行:https://play.golang.org/p/jxAKyVMjnoy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package main

import (
"fmt"
)

func main() {
a := "123"
b := &a

fmt.Println(a)
fmt.Println(b)
fmt.Println(*b)
}

输出结果为:
123
0x40c128
123

并发编程

Go语言的并发是基于 goroutine 的,goroutine 类似于线程,但并非线程。可以将 goroutine 理解为一种虚拟线程。Go语言运行时会参与调度 goroutine,并将 goroutine 合理地分配到每个 CPU 中,最大限度地使用CPU性能。

Go 程序从 main 包的 main() 函数开始,在程序启动时,Go 程序就会为 main() 函数创建一个默认的 goroutine。

下面我们来看一个例子(在线演示:https://play.golang.org/p/U9U-qjuY0t1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package main

import (
"fmt"
"time"
)

func main() {
// 创建一个goroutine
go runing()
// 创建一个匿名的goroutine
go func() {
fmt.Println("喜特:" + time.Now().String())
}()

// 这里sleep一下是因为main方法如果执行完了,main该程序创建的所有goroutine都会退出
time.Sleep(5 * time.Second)
}

func runing() {
fmt.Println("法克:" + time.Now().String())
time.Sleep(3 * time.Second)
}

输出:
法克:2009-11-10 23:00:00 +0000 UTC m=+0.000000001
喜特:2009-11-10 23:00:00 +0000 UTC m=+0.000000001

执行结果说明fuck函数中的sleep三秒并没有影响喜特的输出。

如果说 goroutine 是Go语言程序的并发体的话,那么 channel 就是它们之间的通信机制。一个 channel 是一个通信机制,它可以让一个 goroutine 通过它给另一个 goroutine 发送值信息。每个 channel 都有一个特殊的类型,也就是 channel 可发送数据的类型。一个可以发送 int 类型数据的 channel 一般写为 chan int。

下面我们利用goroutine+channel来实现一个生产消费者模型,示例代码如下:(在线执行:https://play.golang.org/p/lqUBugLdU-I)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package main

import (
"fmt"
"time"
)

func main() {
// 创建一个通道
channel := make(chan int64)

// 异步去生产
go producer(channel)

// 数据消费
consumer(channel)
}

// 生产者
func producer(channel chan<- int64) {
for {
// 将数据写入通道
channel <- time.Now().Unix()
// 睡1秒钟
time.Sleep(time.Second)
}
}

// 消费者
func consumer(channel <-chan int64) {
for {
timestamp := <-channel
fmt.Println(timestamp)
}
}

输出为如下:(每秒钟打印一次)
1257894000
1257894001
1257894002
1257894003

Java程序员觉得不好用的地方

  • 异常处理
  • 没有泛型
  • 不支持多态、重载
  • 不支持注解(但是他的struct中的属性支持tag

参考

Markdown 语法指南

Markdown 语法指南

语法详解

粗体

1
2
**粗体**
__粗体__

斜体

1
2
*斜体*
_斜体_

标题

1
2
3
4
5
6
7
8
9
10
# 一级标题 #
一级标题
====
## 二级标题 ##
二级标题
----
### 三级标题 ###
#### 四级标题 ####
##### 五级标题 #####
###### 六级标题 ######

分割线

1
2
***
---

^上^角

1
2
上角标 x^2^
下角标 H~2~0

++下划线++ 中划线

1
2
++下划线++
~~中划线~~

==标记==

1
==标记==

段落引用

1
2
3
4
> 一级
>> 二级
>>> 三级
...

列表

1
2
3
4
5
6
7
8
9
有序列表
1.
2.
3.
...
无序列表
-
-
...

任务列表

  • 已完成任务
  • 未完成任务
1
2
- [x] 已完成任务
- [ ] 未完成任务

链接

1
2
[链接](www.baidu.com)
![图片描述](http://www.image.com)

代码段落

``` type

代码段落

```

` 代码块 `

1
2
3
4
int main()
{
printf("hello world!");
}

code

表格(table)

1
2
3
4
| 标题1 | 标题2 | 标题3 |
| :-- | :--: | ----: |
| 左对齐 | 居中 | 右对齐 |
| ---------------------- | ------------- | ----------------- |
标题1 标题2 标题3
左对齐 居中 右对齐
———————- ————- —————–

脚注(footnote)

1
hello[^hello]

见底部脚注^hello

表情(emoji)

参考网站: https://www.webpagefx.com/tools/emoji-cheat-sheet/

1
2
3
4
5
:laughing:
:blush:
:smiley:
:)
...

:laughing::blush::smiley::)

$\KaTeX$公式

我们可以渲染公式例如:$x_i + y_i = z_i$和$\sum_{i=1}^n a_i=0$
我们也可以单行渲染
$$\sum_{i=1}^n a_i=0$$
具体可参照katex文档katex支持的函数以及latex文档

布局

::: hljs-left
::: hljs-left
居左
:::
:::

::: hljs-center
::: hljs-center
居中
:::
:::

::: hljs-right
::: hljs-right
居右
:::
:::

定义

术语一

: 定义一

包含有行内标记的术语二

: 定义二

    {一些定义二的文字或代码}

定义二的第三段
1
2
3
4
5
6
7
8
9
10
11
12
术语一

: 定义一

包含有*行内标记*的术语二

: 定义二

{一些定义二的文字或代码}

定义二的第三段

abbr

*[HTML]: Hyper Text Markup Language
*[W3C]: World Wide Web Consortium
HTML 规范由 W3C 维护

1
2
3
*[HTML]: Hyper Text Markup Language
*[W3C]: World Wide Web Consortium
HTML 规范由 W3C 维护

解决配置authorized_keys无法登陆

因为权限问题才无法登陆,这里记录下,方便后面查用。

1
2
sudo chmod 644 ~/.ssh/authorized_keys
sudo chmod 700 ~/.ssh

Golang transaction 事务使用的正确姿势

第一种写法

这种写法非常朴实,程序流程也非常明确,但是事务处理与程序流程嵌入太深,容易遗漏,造成严重的问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
func DoSomething() (err error) {
tx, err := db.Begin()
if err != nil {
return
}


defer func() {
if p := recover(); p != nil {
tx.Rollback()
panic(p) // re-throw panic after Rollback
}
}()


if _, err = tx.Exec(...); err != nil {
tx.Rollback()
return
}
if _, err = tx.Exec(...); err != nil {
tx.Rollback()
return
}
// ...


err = tx.Commit()
return
}

第二种写法

下面这种写法把事务处理从程序流程抽离了出来,不容易遗漏,但是作用域是整个函数,程序流程不是很清晰

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
func DoSomething() (err error) {
tx, err := db.Begin()
if err != nil {
return
}


defer func() {
if p := recover(); p != nil {
tx.Rollback()
panic(p) // re-throw panic after Rollback
} else if err != nil {
tx.Rollback()
} else {
err = tx.Commit()
}
}()


if _, err = tx.Exec(...); err != nil {
return
}
if _, err = tx.Exec(...); err != nil {
return
}
// ...
return
}

第三种写法

写法三是对写法二的进一步封装,写法高级一点,缺点同上

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
func Transact(db *sql.DB, txFunc func(*sql.Tx) error) (err error) {
tx, err := db.Begin()
if err != nil {
return
}


defer func() {
if p := recover(); p != nil {
tx.Rollback()
panic(p) // re-throw panic after Rollback
} else if err != nil {
tx.Rollback()
} else {
err = tx.Commit()
}
}()


err = txFunc(tx)
return err
}


func DoSomething() error {
return Transact(db, func (tx *sql.Tx) error {
if _, err := tx.Exec(...); err != nil {
return err
}
if _, err := tx.Exec(...); err != nil {
return err
}
})
}

我的写法

经过总结和实验,我采用了下面这种写法,defer tx.Rollback() 使得事务回滚始终得到执行。 当 tx.Commit() 执行后,tx.Rollback() 起到关闭事务的作用, 当程序因为某个错误中止,tx.Rollback() 起到回滚事务,同事关闭事务的作用。

普通场景

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func DoSomething() (err error) {
tx, _ := db.Begin()
defer tx.Rollback()

if _, err = tx.Exec(...); err != nil {
return
}
if _, err = tx.Exec(...); err != nil {
return
}
// ...


err = tx.Commit()
return
}

循环场景

(1) 小事务 每次循环提交一次 在循环内部使用这种写法的时候,defer 不能使用,所以要把事务部分抽离到独立的函数当中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
func DoSomething() (err error) {
tx, _ := db.Begin()
defer tx.Rollback()

if _, err = tx.Exec(...); err != nil {
return
}
if _, err = tx.Exec(...); err != nil {
return
}
// ...


err = tx.Commit()
return
}


for {
if err := DoSomething(); err != nil{
// ...
}
}

(2) 大事务 批量提交 大事务的场景和普通场景是一样的,没有任何区别

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
func DoSomething() (err error) {
tx, _ := db.Begin()
defer tx.Rollback()

for{
if _, err = tx.Exec(...); err != nil {
return
}
if _, err = tx.Exec(...); err != nil {
return
}
// ...
}

err = tx.Commit()
return
}

参考链接:
https://stackoverflow.com/questions/16184238/database-sql-tx-detecting-commit-or-rollback
原文地址:
http://hopehook.com/2017/08/21/golang_transaction/

HexoClient1.2.6版本发布

本次更新内容

  • feature:支持hexo特性front-matter #32 #38
  • bugfix:修复一处RCE(任意代码执行)漏洞 #35
  • 升级electron 到最新版本
  • 升级webpack到最新版本,解决老版本漏洞问题

功能预览

image.png
image.png

相关链接

go mod 的使用

从Go1.11开始,golang官方支持了新的依赖管理工具go mod

命令行说明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
➜  ~ go mod
Go mod provides access to operations on modules.

Note that support for modules is built into all the go commands,
not just 'go mod'. For example, day-to-day adding, removing, upgrading,
and downgrading of dependencies should be done using 'go get'.
See 'go help modules' for an overview of module functionality.

Usage:

go mod <command> [arguments]

The commands are:

download download modules to local cache
edit edit go.mod from tools or scripts
graph print module requirement graph
init initialize new module in current directory
tidy add missing and remove unused modules
vendor make vendored copy of dependencies
verify verify dependencies have expected content
why explain why packages or modules are needed

Use "go help mod <command>" for more information about a command.
  • go mod download: 下载依赖的module到本地cache
  • go mod edit: 编辑go.mod
  • go mod graph: 打印模块依赖图
  • go mod init: 在当前目录下初始化go.mod(就是会新建一个go.mod文件)
  • go mod tidy: 整理依赖关系,会添加丢失的module,删除不需要的module
  • go mod vender: 将依赖复制到vendor下
  • go mod verify: 校验依赖
  • go mod why: 解释为什么需要依赖

在新项目中使用

使用go mod并不要求你的项目源码放到$GOPATH下,所以你的新项目可以放到任意你喜欢的路径。在项目根目录下执行go mod init,会生成一个go.mod文件。然后你可以在其中增加你的依赖,如下:

1
2
3
4
5
6
7
8
module github.com/gaoyoubo/xxx

go 1.12

require (
github.com/go-sql-driver/mysql v1.4.1
.... 你的依赖类似这样,添加到这里,一行一条。
)

然后执行go mod download,将依赖下载到本地。这些依赖并不是下载到你的项目目录下,而是会下载到$GOPATH/pkg/mod目录下,这样所有使用go mod的项目都可以共用。

在旧项目中使用

在旧项目中使用非常简单,只需要一下两个步骤:

  • go mod init: 在项目根目录下执行该命令,会在项目根目录下生成一个go.mod文件。
  • go mod tidy: 在项目根目录下执行该命令,go mod会自动分析你当前项目所需要的依赖,并且将他们下载下来。

如何升级依赖

运行 go get -u 将会升级到最新的次要版本或者修订版本(x.y.z, z是修订版本号y是次要版本号)
运行 go get -u=patch 将会升级到最新的修订版本
运行 go get package@version 将会升级到指定的版本

mysql5.x重置密码

This one is for all MySQL-DBA’s, which are working on macOS. Since the Apple OS has a rather peculiar way of starting and stopping MySQL, compared to Linux, you can run into some issues. These problems occur especially, if you have no access to the GUI.

PREPARATION

Put skip-grant-tables into the mysqld section of the my.cnf. A my.cnf can be found in /usr/local/mysql/support-files. You MUST work as root for all the following steps.

1
2
3
4
5
6
7
8
shell> sudo -s
shell> vi /usr/local/mysql/support-files/my-default.cnf

...
[mysqld]
skip-grant-tables
skip-networking
...

Save the configuration file! (In vi this is “[ESC] + :x”)

Continue with stopping MySQL:

1
launchctl unload /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist

Restart MySQL, so skip-grant-tables becomes active:

1
launchctl load /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist

RESET THE PASSWORD

After MySQL is started again, you can log into the CLI and reset the password:

1
2
3
shell> mysql -u root
mysql> FLUSH PRIVILEGES;
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'super-secret-password';

PLAN B

If you are not capable of stopping MySQL in a civilised manner, you can use the more rough way. You can send a SIGTERM to the MySQL-Server:

1
2
shell> ps -aef | grep mysql | grep -v grep
74 28017 1 0 Fri10AM ?? 5:59.50 /usr/local/mysql/bin/mysqld --user=_mysql --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data --plugin-dir=/usr/local/mysql/lib/plugin --log-error=/usr/local/mysql/data/mysqld.local.err --pid-file=/usr/local/mysql/data/mysqld.local.pid

You should receive one line. The second column from the left is the process id. Use this process id to stop the MySQL-Server.

1
shell> kill -15 [process id]

In this example, the command would look like this:

1
shell> kill -15 28017

macOS will restart MySQL, since the process has not stopped correctly. The configuration will be read and the changes to the parameters will become effective. Continue with logging in to the CLI.

CONCLUSION

No matter how secure your MySQL-Password is, it is a lot more important to secure access to the server it self. If your server is not secured by something that prevents access from the internet, it will only take a few minutes for someone with bad intentions to take over your database or worse, the entire server.

Golang和Java构建工具调查

Github:https://github.com/blindpirate/report-of-build-tools-for-java-and-golang

A Survey on Build Tools of Golang and Java

Java

Conclusion

In January 2017, the usage of build tools in Github’s top 1000 Java repositories is as follows:

Tool Name Reference Count
Gradle 627
Maven 264
Ant 52
Npm 4
Bazel 3
Make 1

And the trending over the past 8 years is:

trending

Algorithm

  • Clone top 1000 Java repositories to local disk
  • Analyze the repositories by identity files:
Tool Name Identity Files
Gradle build.gradle
Maven pom.xml
Ant build.xml
Npm package.json
Bazel BUILD
Make Makefile/makefile

How

  • Make sure Git/Groovy 2.4+/JDK 1.7+ are installed.
  • Run groovy GithubTopRankCrawler.groovy -l java -d <path to store the 1000 repos> to clone all repositories locally.
  • Run groovy JavaBuildToolScanner.groovy -d <path to store the 1000 repos> to analyze these repos.

Golang

Conclusion

There are various package management tools for golang as listed here. But which one is the most popular?

The usage of package manage tools in Github’s top 1000 Go repositories is as follows:

Tool Name Url Reference Count (Feb 2017) Reference Count (Nov 2017)
Makefile Makefile 199 181
dep dep N/A 94
godep godep 119 90
govendor govendor 65 84
glide glide 64 77
gvt gvt 25 16
trash trash 7 13
submodule submodule 8 6
gpm/johnny-deps gpm johnny-deps 7 6
glock glock 5 4
gom gom 4 2
gopack gopack 3 2
gopm gopm 3 1
goop goop 1 1
gvend gvend 2 0

dep had a first release in May 2017, did not exist for first stats.

Technically, make is not a package management tool, here it is just for comparison.

Submodule refers to a set of tools which use git submodule to manage dependencies such as manul and Vendetta and so on.

Algorithm

  • Clone top 1000 Go repositories to local disk
  • Analyze the repositories by identity files:
Tool Name Identity Files
godep Godeps/Godeps.json
govendor vendor/vendor.json
gopm .gopmfile
gvt vendor/manifest
gvend vendor.yml
glide glide.yaml or glide.lock
trash vendor.conf
gom Gomfile
bunch bunchfile
goop Goopfile
goat .go.yaml
glock GLOCKFILE
gobs goproject.json
gopack gopack.config
nut Nut.toml
gpm/johnny-deps Godeps
Makefile makefile or Makefile
submodule .gitmodules

How

  • Make sure Git/Groovy 2.4+/JDK 1.7+ are installed.
  • Run groovy GithubTopRankCrawler.groovy -l go -d <path to store the 1000 repos> to clone all repositories locally. You can use -s to do the shallow clone and decrease disk usage.
  • Run groovy GoBuildToolScanner.groovy <path to store the 1000 repos> to analyze these repos.

Git仓库初始化

Create a new repository

1
2
3
4
5
6
git clone git@github.com:gaoyoubo/hexo-client.git
cd user-center-transfer
touch README.md
git add README.md
git commit -m "add README"
git push -u origin master

Existing folder

1
2
3
4
5
6
cd existing_folder
git init
git remote add origin git@github.com:gaoyoubo/hexo-client.git
git add .
git commit -m "Initial commit"
git push -u origin master

Existing Git repository

1
2
3
4
5
cd existing_repo
git remote rename origin old-origin
git remote add origin git@github.com:gaoyoubo/hexo-client.git
git push -u origin --all
git push -u origin --tags

JWT介绍

JWT全称为:JSON Web Token是目前最流行的跨域认证的解决方案。

跨域认证的问题

互联网服务离不开用户认证。一般流程是下面这样。

  1. 用户向服务器发送用户名和密码。
  2. 服务器验证通过后,在当前对话(session)里面保存相关数据,比如用户角色、登录时间等等。
  3. 服务器向用户返回一个 session_id,写入用户的 Cookie。
  4. 用户随后的每一次请求,都会通过 Cookie,将 session_id 传回服务器。
  5. 服务器收到 session_id,找到前期保存的数据,由此得知用户的身份。

image.png

这种模式的问题在于,扩展性不好。单机当然没有问题,如果是服务器集群,或者是跨域的服务导向架构,就要求 session 数据共享,每台服务器都能够读取 session。

举例来说,A 网站和 B 网站是同一家公司的关联服务。现在要求,用户只要在其中一个网站登录,再访问另一个网站就会自动登录,请问怎么实现?

一种解决方案是 session 数据持久化,写入数据库或别的持久层。各种服务收到请求后,都向持久层请求数据。这种方案的优点是架构清晰,缺点是工程量比较大。另外,持久层万一挂了,就会单点失败。

image.png

另一种方案是服务器索性不保存 session 数据了,所有数据都保存在客户端,每次请求都发回服务器。JWT 就是这种方案的一个代表。

JWT的原理

JWT的原则是在服务器身份验证之后,将生成一个JSON对象并将其发送回用户,如下所示。

1
2
3
4
5
{
"username": "admin",
"role": "admin",
"expire": "2018-12-24 20:15:56"
}

以后,用户与服务端通信的时候,都要发回这个 JSON 对象。服务器完全只靠这个对象认定用户身份。为了防止用户篡改数据,服务器在生成这个对象的时候,会加上签名(详见后文)。

服务器就不保存任何 session 数据了,也就是说,服务器变成无状态了,从而比较容易实现扩展。

JWT的数据结构

实际的 JWT 大概就像下面这样。
image.png

它是一个很长的字符串,中间用点.分隔成三个部分。注意,JWT 内部是没有换行的,这里只是为了便于展示,将它写成了几行。

JWT 的三个部分依次如下。

  • Header (头)
  • Payload (负载)
  • Signature (签名)
    写成一行,就是下面的样子:
    1
    Header.Payload.Signature
    image.png
    下面依次介绍这三个部分。

Header 部分是一个 JSON 对象,描述 JWT 的元数据,通常是下面的样子。

1
2
3
4
{
"alg": "HS256",
"typ": "JWT"
}

上面代码中,alg属性表示签名的算法(algorithm),默认是 HMAC SHA256(写成 HS256);typ属性表示这个令牌(token)的类型(type),JWT令牌统一写为JWT。
最后,将上面的 JSON 对象使用 Base64URL 算法(详见后文)转成字符串。

JWT里验证和签名使用的算法,可选择下面的:

JWS 算法名称 描述
HS256 HMAC256 HMAC with SHA-256
HS384 HMAC384 HMAC with SHA-384
HS512 HMAC512 HMAC with SHA-512
RS256 RSA256 RSASSA-PKCS1-v1_5 with SHA-256
RS384 RSA384 RSASSA-PKCS1-v1_5 with SHA-384
RS512 RSA512 RSASSA-PKCS1-v1_5 with SHA-512
ES256 ECDSA256 ECDSA with curve P-256 and SHA-256
ES384 ECDSA384 ECDSA with curve P-384 and SHA-384
ES512 ECDSA512 ECDSA with curve P-521 and SHA-512

Payload

Payload 部分也是一个 JSON 对象,用来存放实际需要传递的数据。JWT 规定了7个官方字段,供选用。

  • iss (issuer):签发人
  • exp (expiration time):过期时间
  • sub (subject):主题
  • aud (audience):受众
  • nbf (Not Before):生效时间
  • iat (Issued At):签发时间
  • jti (JWT ID):编号
    除了官方字段,你还可以在这个部分定义私有字段,下面就是一个例子。
    1
    2
    3
    4
    5
    {
    "sub": "1234567890",
    "name": "John Doe",
    "admin": true
    }
    注意,JWT 默认是不加密的,任何人都可以读到,所以不要把秘密信息放在这个部分。
    这个 JSON 对象也要使用 Base64URL 算法转成字符串。

Signature

Signature 部分是对前两部分的签名,防止数据篡改。

首先,需要指定一个密钥(secret)。这个密钥只有服务器才知道,不能泄露给用户。然后,使用 Header 里面指定的签名算法(默认是 HMAC SHA256),按照下面的公式产生签名。

1
2
3
4
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret)

算出签名以后,把 Header、Payload、Signature 三个部分拼成一个字符串,每个部分之间用.分隔,就可以返回给用户。

Base64URL

前面提到,Header 和 Payload 串型化的算法是 Base64URL。这个算法跟 Base64 算法基本类似,但有一些小的不同。

JWT 作为一个令牌(token),有些场合可能会放到 URL(比如 api.example.com/?token=xxx)。Base64 有三个字符+/=,在 URL 里面有特殊含义,所以要被替换掉:=被省略,+替换成-/替换成_。这就是Base64URL 算法。

JWT的使用方式

客户端收到服务器返回的 JWT,可以储存在 Cookie 里面,也可以储存在 localStorage。

此后,客户端每次与服务器通信,都要带上这个 JWT。你可以把它放在 Cookie 里面自动发送,但是这样不能跨域,所以更好的做法是放在 HTTP 请求的头信息Authorization字段里面。

1
Authorization: Bearer <token>

另一种做法是,跨域的时候,JWT 就放在 POST 请求的数据体里面。

JWT 的几个特点

  • JWT 默认是不加密,但也是可以加密的。生成原始 Token 以后,可以用密钥再加密一次。
  • JWT 不加密的情况下,不能将秘密数据写入 JWT。
  • JWT 不仅可以用于认证,也可以用于交换信息。有效使用 JWT,可以降低服务器查询数据库的次数。
  • JWT 的最大缺点是,由于服务器不保存 session 状态,因此无法在使用过程中废止某个 token,或者更改 token 的权限。也就是说,一旦 JWT 签发了,在到期之前就会始终有效,除非服务器部署额外的逻辑。
  • JWT 本身包含了认证信息,一旦泄露,任何人都可以获得该令牌的所有权限。为了减少盗用,JWT 的有效期应该设置得比较短。对于一些比较重要的权限,使用时应该再次对用户进行认证。
  • 为了减少盗用,JWT 不应该使用 HTTP 协议明码传输,要使用 HTTPS 协议传输。

参考

使用AppVeyor和Travis自动编译Electron全平台应用

package.json配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
{
"name": "HexoClient",
"version": "1.2.2",
"author": "......",
"description": "Hexo 桌面客户端",
"license": "Apache License, Version 2.0",
"homepage": "https://github.com/gaoyoubo/hexo-client",
"repository": {
"type": "git",
"url": "https://github.com/gaoyoubo/hexo-client.git"
},
"main": "./dist/electron/main.js",
"scripts": {
"build": "node .electron-vue/build.js && electron-builder --publish onTagOrDraft"
......
},
"build": {
"appId": "org.mspring.hexo.client",
"productName": "HexoClient",
"directories": {
"output": "build"
},
"files": [
"dist/electron/**/*",
"build/icons/*"
],
"publish": {
"provider": "github",
"owner": "gaoyoubo",
"repo": "hexo-client"
},
"dmg": {
"contents": [
{
"x": 410,
"y": 150,
"type": "link",
"path": "/Applications"
},
{
"x": 130,
"y": 150,
"type": "file"
}
]
},
"mac": {
"icon": "build/icons/icon.icns"
},
"win": {
"target": "nsis",
"icon": "build/icons/icon.ico"
},
"linux": {
"category": "Utility",
"target": [
{
"target": "AppImage",
"arch": [
"x64",
"ia32"
]
},
{
"target": "deb",
"arch": [
"x64",
"ia32"
]
},
{
"target": "rpm",
"arch": [
"x64",
"ia32"
]
}
],
"icon": "build/icons"
}
},
......
}

build配置

electron-builder支持构建多个平台安装包,上面的配置中我配置了Windows、macos、linux,可以直接拷贝使用,如果想了解更多可以看这篇官方出品的文档:https://www.electron.build/configuration/configuration

构建命令配置

1
node .electron-vue/build.js && electron-builder --publish onTagOrDraft

可以看到后面的参数--publish onTagOrDraft他的意思是,当在标签中提交,或github中存在draft发布版本的时候触发publish操作,这个时候会自动将构建好的包上传到github releases中。publish配置的取值如下:

Value Description
onTag on tag push only
onTagOrDraft on tag push or if draft release exists
always always publish
never never publish

参考:

Hexo1.2.0发布,全新的UI布局

Hexo1.2.0发布,全新的UI布局。

之前一直觉得HexoClient的ui太不像一个原生应用,一眼就能看出是网页做的。同样是基于electron,vscode、atom等应用的ui看起来就特别正规、好看,所以这次周末抽一天时间调整一下UI。

本次更新内容

  • MacOS下无边框样式
  • 调整菜单栏布局
  • 修改UI配色和界面细节
  • 修复初始化时选择hexo目录失败的问题
  • 升级electron版本到3.x
  • 其他细节修改

下载地址

Mac版:https://pan.baidu.com/s/1E-5KrusoBuFGRTunTBqPJQ 提取码:2v2q
Windows版本:请自行源码编译。
Linux版本:请自行源码编译。

项目地址

Github: https://github.com/gaoyoubo/hexo-client
码云:https://gitee.com/gaoyoubo/hexo-client

TODO

  • 自动初始化hexo
  • 文章筛选、搜索

搬瓦工使用笔记

之前一直使用朋友的vpn进行翻墙,今天突然发现用不了了,同事强烈推荐使用搬瓦工https://bwh8.net ),他们反馈很稳定。于是就去官网上买了一个最低配的,配置如下:

1
2
3
4
5
6
SSD: 10 GB RAID-10
RAM: 512 MB
CPU: 1x Intel Xeon
Transfer: 500 GB/mo
Link speed: 1 Gigabit
Multiple locations

价格:$19.99/year

购买的时候可以输入优惠码,优惠码自行百度去,有很多资源。我找了个优惠码,优惠了6.25%

接下来就是配置Shadowsocks Server了, 之前网上的教程中都会看到虚拟机vps的控制台会有一个Shadowsocks Server的选项,进去之后能够一键安装配置该服务,但是我的控制台却没有这个选项,在网上找到了下面一段话。

注:最近很多新购买的服务器在VPS管理面板没有“Shadowsocks server”这一项,若是发生此原因,请按如下操作即可正常安装!若页面中没有Shadowsocks Server这一项,说明一键搭建SS功能被去掉了,这时候需要在当前浏览器的新标签中打开以下网址:
https://kiwivm.64clouds.com/main-exec.php?mode=extras_shadowsocks 打开以后就是安装页面,点击页面中的Install Shadowsocks Server安装即可(安装前提是服务器已打开已运行)。

目前已经按照上面链接中的步骤搞定翻墙了。

另外附上Shadowsocks-NG下载地址:https://github.com/shadowsocks/ShadowsocksX-NG/releases



Java学习资料

前几天突然有个姑娘加我的QQ(不知道哪儿来的我的QQ),让我参加他们免费的公开课,然后给我分享Java学习资料,我以为是会给我发几本书,就参加了,没想到是一个txt文件😂,内容如下:

Allen-架构师必备技能-分库分表应对数据量过大
链接:https://pan.baidu.com/s/1OF4RUHvRk98pBRdUiifH2g 密码:n4ev

Allen-互联网安全话题-使用https保障你的敏感数据不再裸奔
链接:https://pan.baidu.com/s/1qz23y-3ahaGua4YH02KTyw 密码:fgh0

Tony-多线程Future模式-写出支撑海量并发连接的服务端代码
链接:https://pan.baidu.com/s/1NwzNRxUB0_DPNQo2IW_Xhg 密码:0fpw

Tony-前后端分离架构分析与实现
链接:https://pan.baidu.com/s/1b7XnTibtqW26YCHfuAXkyA 密码:ah24

Tony-高并发系统架构之负载均衡全方位解析
链接:https://pan.baidu.com/s/1a87EH1Xe20O4XYZaNRo-hw 密码:p52e

Tony-学会举一反三-从Redis看RPC原理
链接:https://pan.baidu.com/s/1disSAbJo-01ESCu6_rTHYQ 密码:ih47

-Mike-分布式系统架构技能—zookeeper实现分布式锁
链接:https://pan.baidu.com/s/1adhFuoUsz1sMQTnWNGoKPA 密码:gjzh

Tony-数据库连接池原理源码分析
链接:https://pan.baidu.com/s/1uBiBBt-tJVSz_5t5p4jG3A 密码:jqo6

Allen-深入SpringMVC原理老司机带你手写自己的MVC框架
链接:https://pan.baidu.com/s/1rlhZCSqXaZpXWM_V5CA7EQ 密码:vysj

Tony-JVM类加载机制之JAVA热部署实战开发
链接:https://pan.baidu.com/s/1JSLGrG0k44um7weQcq5rvg 密码:twn3

Tony-实战高并发系统缓存雪崩场景重现及解决方案
链接:https://pan.baidu.com/s/1i8Q7sPNEcUIPYBuqFerRwQ 密码:lwgj

Mike-解密spring-boot-starter
链接:https://pan.baidu.com/s/12-1N3RTb68l3QfUOxSG1jQ 密码:sodb

Tony-细说springcloud微服务架构之客户端负载均衡
链接:https://pan.baidu.com/s/1VK3mMTkKYzRU4G9YXwlOLg 密码:achq

账号中心服务线上稳定一年纪念

这台服务由三台机器负载,每日处理一亿四千万+次请求,线上稳定运营一年多,未出现任何故障,如果不是这次需求变动还能继续稳定运行。在重启县截图纪念一下。


TOP 10开源的推荐系统简介

转载自:http://ibillxia.github.io/blog/2014/03/10/top-10-open-source-recommendation-systems/

最近这两年推荐系统特别火,本文搜集整理了一些比较好的开源推荐系统,即有轻量级的适用于做研究的SVDFeature、LibMF、LibFM等,也有重量级的适用于工业系统的 Mahout、Oryx、EasyRecd等

SVDFeature

主页:http://svdfeature.apexlab.org/wiki/Main_Page 语言:C++
一个feature-based协同过滤和排序工具,由上海交大Apex实验室开发,代码质量较高。在KDD Cup 2012中获得第一名,KDD Cup 2011中获得第三名,相关论文 发表在2012的JMLR中,这足以说明它的高大上。
SVDFeature包含一个很灵活的Matrix Factorization推荐框架,能方便的实现SVD、SVD++等方法, 是单模型推荐算法中精度最高的一种。SVDFeature代码精炼,可以用 相对较少的内存实现较大规模的单机版矩阵分解运算。另外含有Logistic regression的model,可以很方便的用来进行ensemble。

LibMF

主页:http://www.csie.ntu.edu.tw/~cjlin/libmf/ 语言:C++
作者Chih-Jen Lin来自大名鼎鼎的台湾国立大学,他们在机器学习领域享有盛名,近年连续多届KDD Cup竞赛上均 获得优异成绩,并曾连续多年获得冠军。台湾大学的风格非常务实,业界常用的LibSVM, Liblinear等都是他们开发的,开源代码的效率和质量都非常高。
LibMF在矩阵分解的并行化方面作出了很好的贡献,针对SGD(随即梯度下降)优化方法在并行计算中存在的locking problem和memory discontinuity问题,提出了一种 矩阵分解的高效算法FPSGD(Fast Parallel SGD),根据计算节点的个数来划分评分矩阵block,并分配计算节点。系统介绍可以见这篇 论文(ACM Recsys 2013的 Best paper Award)。

LibFM

主页:http://www.libfm.org/ 语言:C++
作者是德国Konstanz大学的Steffen Rendle,他用LibFM同时玩转KDD Cup 2012 Track1和Track2两个子竞赛单元,都取得了很好的成绩,说明LibFM是非常管用的利器。
LibFM是专门用于矩阵分解的利器,尤其是其中实现了MCMC(Markov Chain Monte Carlo)优化算法,比常见的SGD优化方法精度要高,但运算速度要慢一些。当然LibFM中还 实现了SGD、SGDA(Adaptive SGD)、ALS(Alternating Least Squares)等算法。

Lenskit

主页:http://lenskit.grouplens.org/ 语言Java

这个Java开发的开源推荐系统,来自美国的明尼苏达大学的GroupLens团队,也是推荐领域知名的测试数据集Movielens的作者。
该源码托管在GitHub上,https://github.com/grouplens/lenskit。主要包含lenskit-api,lenskit-core, lenskit-knn,lenskit-svd,lenskit-slopone,lenskit-parent,lenskit-data-structures,lenskit-eval,lenskit-test等模块,主要实现了k-NN,SVD,Slope-One等 典型的推荐系统算法。

GraphLab

主页:GraphLab - Collaborative Filtering 语言:C++
Graphlab是基于C++开发的一个高性能分布式graph处理挖掘系统,特点是对迭代的并行计算处理能力强(这方面是hadoop的弱项),由于功能独到,GraphLab在业界名声很响。 用GraphLab来进行大数据量的random walk或graph-based的推荐算法非常有效。Graphlab虽然名气比较响亮(CMU开发),但是对一般数据量的应用来说可能还用不上。
GraphLab主要实现了ALS,CCD++,SGD,Bias-SGD,SVD++,Weighted-ALS,Sparse-ALS,Non-negative Matrix Factorization,Restarted Lanczos Algorithm等算法。

Mahout

主页:http://mahout.apache.org/ 语言:Java
Mahout 是 Apache Software Foundation (ASF) 开发的一个全新的开源项目,其主要目标是创建一些可伸缩的机器学习算法,供开发人员在 Apache 在许可下免费 使用。Mahout项目是由 Apache Lucene社区中对机器学习感兴趣的一些成员发起的,他们希望建立一个可靠、文档翔实、可伸缩的项目,在其中实现一些常见的用于 聚类和分类的机器学习算法。该社区最初基于 Ngetal. 的文章 “Map-Reduce for Machine Learning on Multicore”,但此后在发展中又并入了更多广泛的机器学习 方法,包括Collaborative Filtering(CF),Dimensionality Reduction,Topic Models等。此外,通过使用 Apache Hadoop 库,Mahout 可以有效地扩展到云中。
在Mahout的Recommendation类算法中,主要有User-Based CF,Item-Based CF,ALS,ALS on Implicit Feedback,Weighted MF,SVD++,Parallel SGD等。

Myrrix

主页:http://myrrix.com/ 语言:Java
Myrrix最初是Mahout的作者之一Sean Owen基于Mahout开发的一个试验性质的推荐系统。目前Myrrix已经是一个完整的、实时的、可扩展的集群和推荐系统,主要 架构分为两部分:服务层:在线服务,响应请求、数据读入、提供实时推荐;计算层:用于分布式离线计算,在后台使用分布式机器学习算法为服务层更新机器学习 模型。Myrrix使用这两个层构建了一个完整的推荐系统,服务层是一个HTTP服务器,能够接收更新,并在毫秒级别内计算出更新结果。服务层可以单独使用,无需 计算层,它会在本地运行机器学习算法。计算层也可以单独使用,其本质是一系列的Hadoop jobs。目前Myrrix以被 Cloudera 并入Oryx项目。

EasyRec

主页:http://easyrec.org/ 语言:Java
EasyRec是一个易集成、易扩展、功能强大且具有可视化管理的推荐系统,更像一个完整的推荐产品,包括了数据录入模块、管理模块、推荐挖掘、离线分析等。 EasyRec可以同时给多个不同的网站提供推荐服务,通过tenant来区分不同的网站。架设EasyRec服务器,为网站申请tenant,通过tenant就可以很方便的集成到 网站中。通过各种不同的数据收集(view,buy.rating)API收集到网站的用户行为,EasyRec通过离线分析,就可以产生推荐信息,您的网站就可以通过 Recommendations和Community Rankings来进行推荐业务的实现。

Waffles

主页:http://waffles.sourceforge.net/ 语言:C++
Waffles英文原意是蜂蜜甜饼,在这里却指代一个非常强大的机器学习的开源工具包。Waffles里包含的算法特别多,涉及机器学习的方方面面,推荐系统位于 其中的Waffles_recommend tool,大概只占整个Waffles的1/10的内容,其它还有分类、聚类、采样、降维、数据可视化、音频处理等许许多多工具包,估计 能与之媲美的也就数Weka了。

RapidMiner

主页:http://rapidminer.com/ 语言:Java
RapidMiner(前身是Yale)是一个比较成熟的数据挖掘解决方案,包括常见的机器学习、NLP、推荐、预测等方法(推荐只占其中很小一部分),而且带有GUI的 数据分析环境,数据ETL、预处理、可视化、评估、部署等整套系统都有。另外RapidMiner提供commercial license,提供R语言接口,感觉在向着一个商用的 数据挖掘公司的方向在前进。


开源的推荐系统大大小小的还有很多,以上只是介绍了一些在学术界和工业界比较流行的TOP 10,而且基本上都是用C++/Java实现的,在参考资料[1]、[2]中还提 到的有Crab(Python)、CofiRank(C++)、MyMediaLite(.NET/C#)、PREA(Java)、Python-recsys(Python)、Recommendable(Ruby)、Recommenderlab(R)、 Oryx(Java)、recommendify(Ruby)、RecDB(SQL)等等,当然GitHub上还有更多。。。即有适合单机运行的,也有适合集群的。虽然使用的编程语言不同,但实现 的算法都大同小异,主要是SVD、SGD、ALS、MF、CF及其改进算法等。

参考资料

小米手机安装Charles证书

平时使用Charles进行接口抓包,新换小米手机之后发现按照之前的流程安装Charles ssl证书不好使,百度了好久才找到一下解决办法。

  • 使用第三方浏览器(我用的是QQ浏览器)下载.pem 格式的文件
  • 将这个文件放入小米的Download文件夹下
  • 将.pem文件修改为.crt 格式
  • 设置—更多设置—系统安全—加密与凭据—从存储设备安装–选择Download文件夹下的文件
  • Finish~~

javacv使用笔记

使用过程中遇到的异常

异常:Could not initialize class org.bytedeco.javacpp.avutil

1
2
3
4
5
6
7
8
Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class org.bytedeco.javacpp.avutil
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:274)
at org.bytedeco.javacpp.Loader.load(Loader.java:385)
at org.bytedeco.javacpp.Loader.load(Loader.java:353)
at org.bytedeco.javacpp.avformat$AVFormatContext.<clinit>(avformat.java:2249)
at org.bytedeco.javacv.FFmpegFrameGrabber.startUnsafe(FFmpegFrameGrabber.java:346)
at org.bytedeco.javacv.FFmpegFrameGrabber.start(FFmpegFrameGrabber.java:340)

解决办法:

1
mvn package exec:java -Dplatform.dependencies -Dexec.mainClass=Demo

警告:Warning: data is not aligned! This can lead to a speedloss

出现这个警告是因为ffmpeg要求视频的宽度必须是32的倍数,高度必须是2的倍数,按要求修改下宽高就好了。

使用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import com.google.common.collect.Lists;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.bytedeco.javacpp.avcodec;
import org.bytedeco.javacpp.opencv_core;
import org.bytedeco.javacpp.opencv_imgcodecs;
import org.bytedeco.javacv.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Collections;
import java.util.List;

/**
* @author Gao Youbo
* @since 2018-08-15 16:43
*/
public class OpenCVUtils {
public static void main(String[] args) throws Exception {
List<BufferedImage> images = grab(new File("/data/opencv/test.mp4"));
int i = 1;
for (BufferedImage image : images) {
ImageIO.write(image, "jpg", new File("/data/opencv/frame/" + i + ".jpg"));
i++;
}

// grabAudioFromVideo(new File("/data/opencv/test.mp4"), new File("/data/opencv/test.aac"));

List<File> files = Lists.newArrayList(FileUtils.listFiles(new File("/data/opencv/frame/"), new String[]{"jpg"}, false));
Collections.sort(files, (o1, o2) -> {
int i1 = NumberUtils.toInt(StringUtils.substringBefore(o1.getName(), "."));
int i2 = NumberUtils.toInt(StringUtils.substringBefore(o2.getName(), "."));
return Integer.compare(i1, i2);
});
record("/data/opencv/out.mp4", files, new File("/data/opencv/test.aac"), 544, 960);
}

/**
* 将多个图片文件合成视频
*
* @param output 输出文件
* @param images 序列帧图片
* @param audioFile 音频
* @param width 宽
* @param height 高
* @throws Exception
*/
public static void record(String output, List<File> images, File audioFile, int width, int height) throws Exception {
try (FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(output, width, height);
FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(audioFile)) {
recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
recorder.setFormat("mp4");
recorder.setFrameRate(30);
recorder.setAudioBitrate(192000);
recorder.setAudioQuality(0);
recorder.setSampleRate(44100);
recorder.setAudioChannels(2);
recorder.start();

OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();
for (File file : images) {
opencv_core.IplImage image = opencv_imgcodecs.cvLoadImage(file.getPath());
recorder.record(converter.convert(image));
opencv_core.cvReleaseImage(image);
}

grabber.start();
Frame frame;
while ((frame = grabber.grabSamples()) != null) {
recorder.setTimestamp(frame.timestamp);
recorder.recordSamples(frame.sampleRate, frame.audioChannels, frame.samples);
}
}
}

/**
* 从视频中将每一帧的图片提取出来
*
* @param video
* @return
* @throws FrameGrabber.Exception
*/
public static List<BufferedImage> grab(File video) throws Exception {
try (FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(video.getPath())) {
grabber.start();

List<BufferedImage> images = Lists.newArrayList();
Frame frame;
while ((frame = grabber.grabImage()) != null) {
images.add(Java2DFrameUtils.toBufferedImage(frame));
}
return images;
}
}

/**
* 从视频中提取出音频
*
* @param video
* @param outputAudio
*/
public static void grabAudioFromVideo(File video, File outputAudio) throws Exception {
try (FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(video);
FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(outputAudio, 1)) {
grabber.start();
recorder.setAudioCodec(avcodec.AV_CODEC_ID_AAC);
recorder.start();

Frame frame;
while ((frame = grabber.grab()) != null) {
if (frame.audioChannels == 1) {
recorder.recordSamples(frame.sampleRate, frame.audioChannels, frame.samples);
}
}
}
}

}

图片合成视频简单的封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
private static class VideoRecorder implements Closeable {
private FFmpegFrameRecorder recorder;

public VideoRecorder(String output, int width, int height) throws FrameRecorder.Exception {
recorder = new FFmpegFrameRecorder(output, width, height);
recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
recorder.setFormat("mp4");
recorder.setFrameRate(FPS);
recorder.setAudioBitrate(192000);
recorder.setAudioQuality(0);
recorder.setSampleRate(44100);
recorder.setAudioChannels(2);
recorder.start();
}

public void addFrame(BufferedImage image) throws FrameRecorder.Exception {
Frame frame = Java2DFrameUtils.toFrame(image);
recorder.record(frame, avutil.AV_PIX_FMT_ARGB);
}

public void addAudio(File audioFile) throws FrameGrabber.Exception, FrameRecorder.Exception {
if (audioFile == null || !audioFile.exists()) {
return;
}
try (FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(audioFile)) {
grabber.start();
Frame frame;
while ((frame = grabber.grabSamples()) != null) {
recorder.recordSamples(frame.sampleRate, frame.audioChannels, frame.samples);
}
}
}

@Override
public void close() throws IOException {
recorder.close();
}
}

解决maven打包时将不必要的包引入进来的问题

我在实际使用中只用到了ffmpeg,但是打包的时候却将flycapture、libdc1394、libfreenect、artoolkitplus、tesseract…等包都打进来了,这些都是我不需要的,下面贴出我的maven配置示例。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<properties>
<javacpp.version>1.4.2</javacpp.version>
<!-- 这里要根据自己的平台选择不同的依赖 -->
<!--<javacpp.platform.dependencies>linux-x86_64</javacpp.platform.dependencies>-->
<javacpp.platform.dependencies>macosx-x86_64</javacpp.platform.dependencies>
</properties>
<dependencies>
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv</artifactId>
<version>${javacpp.version}</version>
<exclusions>
<exclusion>
<groupId>org.bytedeco.javacpp-presets</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.bytedeco.javacpp-presets</groupId>
<artifactId>opencv</artifactId>
<version>3.4.2-${javacpp.version}</version>
</dependency>
<dependency>
<groupId>org.bytedeco.javacpp-presets</groupId>
<artifactId>ffmpeg</artifactId>
<version>4.0.1-${javacpp.version}</version>
</dependency>
<dependency>
<groupId>org.bytedeco.javacpp-presets</groupId>
<artifactId>ffmpeg</artifactId>
<version>4.0.1-${javacpp.version}</version>
<classifier>${javacpp.platform.dependencies}</classifier>
</dependency>
</dependencies>

收藏两首程序员打油诗

1
2
3
4
5
6
7
8
商女不知亡国恨,一天到晚敲代码。
举头望明月,低头敲代码。
洛阳亲友如相问,就说我在敲代码。
少壮不努力,老大敲代码。
垂死病中惊坐起,今天还没敲代码。
生当作人杰,死亦敲代码。
人生自古谁无死,来生继续敲代码。
众里寻他千百度,蓦然回首,那人正在敲代码。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
写字楼里写字间,写字间里程序员;程序人员写程序,又拿程序换酒钱。
酒醒只在网上坐,酒醉还来网下眠;酒醉酒醒日复日,网上网下年复年。
宁愿老死程序间,只要老板多发钱;小车大房不去想,撰个二千好过年。
若要见识新世面,公务员比程序员;一个在天一在地,而且还比我们闲。
别人看我穿白领,我看别人穿名牌;天生我才写程序,臀大近视肩周炎。

年复一年春光度,度得他人做老板;老板扣我薄酒钱,没有酒钱怎过年。
春光逝去皱纹起,作起程序也委靡;来到水源把水灌,打死不做程序员。
别人笑我忒疯癫,我笑他人命太贱;状元三百六十行,偏偏来做程序员。
但愿老死电脑间,不愿鞠躬老板前;奔驰宝马贵者趣,公交自行程序员。
别人笑我忒疯癫,我笑自己命太贱;不见满街漂亮妹,哪个归得程序员。

不想只挣打工钱,那个老板愿发钱;小车大房咱要想,任我享用多悠闲。
比尔能搞个微软,我咋不能捞点钱;一个在天一在地,定有一日乾坤翻。
我在天来他在地,纵横天下山水间;傲视武林豪杰墓,一樽还垒风月山。
电脑面前眼发直,眼镜下面泪茫茫;做梦发财好几亿,从此不用手指忙。
哪知梦醒手空空,老板看到把我训;待到老时眼发花,走路不知哪是家。

小农村里小民房,小民房里小民工;小民工人写程序,又拿代码讨赏钱。
钱空只在代码中,钱醉仍在代码间;有钱无钱日复日,码上码下年复年。
但愿老死代码间,不愿鞠躬奥迪前,奥迪奔驰贵者趣,程序代码贫者缘。
若将贫贱比贫者,一在平地一在天;若将贫贱比车马,他得驱驰我得闲。
别人笑我忒疯癫,我笑他人看不穿;不见盖茨两手间,财权富贵世人鉴。

DelayQueue使用

DelayQueue特性

  • 队列中的元素都必须实现Delayed,元素可以指定延迟消费时长。
  • 实现了BlockingQueue接口,所以他是一个阻塞队列。
  • 本质上是基于PriorityQueue实现的。

贴一段我在实际生产环境中使用到代码

队列管理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
* @author Gao Youbo
* @since 2018-07-26 19:53
*/
public class DelayQueueManager {
private static final Logger LOG = LoggerFactory.getLogger(DelayQueueManager.class);

private String name;
private ExecutorService executor;
private Thread monitorThread;
private DelayQueue<DelayTask<?>> delayQueue; // 延时队列

public DelayQueueManager(String name, int poolSize) {
this.name = name;
this.executor = Executors.newFixedThreadPool(poolSize);
this.delayQueue = new DelayQueue<>();
init();
}

/**
* 初始化
*/
private void init() {
monitorThread = new Thread(() -> {
execute();
}, "DelayQueueMonitor-" + name);
monitorThread.start();
}

private void execute() {
while (true) {
LOG.info("当前延时任务数量:" + delayQueue.size());
try {
// 从延时队列中获取任务
DelayTask<?> delayTask = delayQueue.take();
if (delayTask != null) {
Runnable task = delayTask.getTask();
if (task != null) {
// 提交到线程池执行task
executor.execute(task);
}
}
} catch (Exception e) {
LOG.error(null, e);
}
}
}

/**
* 添加任务
*
* @param id 任务编号
* @param task 任务
* @param time 延时时间
* @param unit 时间单位
*/
public void put(String id, Runnable task, long time, TimeUnit unit) {
long timeout = TimeUnit.MILLISECONDS.convert(time, unit);
long delayTimeMillis = System.currentTimeMillis() + timeout;
delayQueue.put(new DelayTask<>(id, delayTimeMillis, task));
}

/**
* 添加任务
*
* @param id 任务编号
* @param task 任务
* @param delayTimeMillis 延迟到什么时间点
*/
public void putAt(String id, Runnable task, long delayTimeMillis) {
delayQueue.put(new DelayTask<>(id, delayTimeMillis, task));
}

/**
* 根据任务编号删除任务
*
* @param id
* @return
*/
public boolean removeTaskById(String id) {
DelayTask task = new DelayTask(id, 0, null);
return delayQueue.remove(task);
}

/**
* 删除任务
*
* @param task
* @return
*/
public boolean removeTask(DelayTask task) {
return delayQueue.remove(task);
}
}

延迟任务对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

import java.util.Objects;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
* @author Gao Youbo
* @since 2018-07-26 19:54
*/
public class DelayTask<T extends Runnable> implements Delayed {
private final String id;
private final long delayTimeMillis; // 延迟到什么时间点执行
private final T task; // 任务

public DelayTask(String id, long delayTimeMillis, T task) {
this.id = id;
this.delayTimeMillis = delayTimeMillis;
this.task = task;
}

public T getTask() {
return task;
}

@Override
public int compareTo(Delayed o) {
DelayTask other = (DelayTask) o;
long diff = delayTimeMillis - other.delayTimeMillis;
if (diff > 0) {
return 1;
} else if (diff < 0) {
return -1;
} else {
return 0;
}
}

@Override
public long getDelay(TimeUnit unit) {
return unit.convert(this.delayTimeMillis - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DelayTask<?> delayTask = (DelayTask<?>) o;
return Objects.equals(id, delayTask.id);
}

@Override
public int hashCode() {
return Objects.hash(id);
}
}

npm发布自己的包

  1. 如果没有账号,那么使用npm adduser去创建账号,中间会引导你输入用户名、密码、邮箱。
  2. 如果已经有账号,需要使用npm login去登录,同样会引导你输入正确的用户名、密码、邮箱。
  3. 登录成功之后使用npm publish将自己的包发不上去。

ffmpeg常用命令总结

音频格式转换

1
2
3
4
5
6
ffmpeg -y  -i aidemo.mp3  -acodec pcm_s16le -f s16le -ac 1 -ar 16000 16k.pcm 

// -acodec pcm_s16le pcm_s16le 16bits 编码器
// -f s16le 保存为16bits pcm格式
// -ac 1 单声道
// -ar 16000 16000采样率

查看音频格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
ffprobe -v quiet -print_format json -show_streams  aidemo.mp3

输出如下:
{
"streams": [
{
"index": 0,
"codec_name": "mp3", // mp3 格式
"codec_long_name": "MP3 (MPEG audio layer 3)",
"codec_type": "audio",
"codec_time_base": "1/16000",
"codec_tag_string": "[0][0][0][0]",
"codec_tag": "0x0000",
"sample_fmt": "s16p",
"sample_rate": "16000", // 16000采样率
"channels": 1, // 单声道
"channel_layout": "mono",
"bits_per_sample": 0,
"r_frame_rate": "0/0",
"avg_frame_rate": "0/0",
"time_base": "1/14112000",
"start_pts": 0,
"start_time": "0.000000",
"duration_ts": 259096320,
"duration": "18.360000",
"bit_rate": "16000",
"disposition": {
"default": 0,
"dub": 0,
"original": 0,
"comment": 0,
"lyrics": 0,
"karaoke": 0,
"forced": 0,
"hearing_impaired": 0,
"visual_impaired": 0,
"clean_effects": 0,
"attached_pic": 0,
"timed_thumbnails": 0
}
}
]
}

Guava Range使用方法

概念 表示范围 guava对应功能方法
(a..b) {x | a < x < b} open(C, C)
[a..b] {x | a <= x <= b} closed(C, C)
[a..b) {x | a <= x < b} closedOpen(C, C)
(a..b] {x | a < x <= b} openClosed(C, C)
(a..+∞) {x | x > a} greaterThan(C)
[a..+∞) {x | x >= a} atLeast(C)
(-∞..b) {x | x < b} lessThan(C)
(-∞..b] {x | x <= b} atMost(C)
(-∞..+∞) all values all()

微信红包的架构设计简介

转载自:http://colobu.com/2015/05/04/weixin-red-packets-design-discussion/

背景:有某个朋友在朋友圈咨询微信红包的架构,于是乎有了下面的文字(有误请提出,谢谢)
概况:2014年微信红包使用数据库硬抗整个流量,2015年使用cache抗流量。

微信的金额什么时候算?

答:微信金额是拆的时候实时算出来,不是预先分配的,采用的是纯内存计算,不需要预算空间存储。
采取实时计算金额的考虑:预算需要占存储,实时效率很高,预算才效率低。

实时性:为什么明明抢到红包,点开后发现没有?

答:2014年的红包一点开就知道金额,分两次操作,先抢到金额,然后再转账。
2015年的红包的拆和抢是分离的,需要点两次,因此会出现抢到红包了,但点开后告知红包已经被领完的状况。进入到第一个页面不代表抢到,只表示当时红包还有。

分配:红包里的金额怎么算?为什么出现各个红包金额相差很大?

答:随机,额度在0.01和剩余平均值 * 2之间。 例如:发100块钱,总共10个红包,那么平均值是10块钱一个,那么发出来的红包的额度在0.01元~20元之间波动。
当前面3个红包总共被领了40块钱时,剩下60块钱,总共7个红包,那么这7个红包的额度在:0.01~(60/7 * 2)=17.14之间。
注意:这里的算法是每被抢一个后,剩下的会再次执行上面的这样的算法(Tim老师也觉得上述算法太复杂,不知基于什么样的考虑)。

这样算下去,会超过最开始的全部金额,因此到了最后面如果不够这么算,那么会采取如下算法:保证剩余用户能拿到最低1分钱即可。
如果前面的人手气不好,那么后面的余额越多,红包额度也就越多,因此实际概率一样的。

红包的设计

答:微信从财付通拉取金额数据过来,生成个数/红包类型/金额放到redis集群里,app端将红包ID的请求放入请求队列中,如果发现超过红包的个数,直接返回。根据红包的逻辑处理成功得到令牌请求,则由财付通进行一致性调用,通过像比特币一样,两边保存交易记录,交易后交给第三方服务审计,如果交易过程中出现不一致就强制回归。

并发性处理:红包如何计算被抢完?

答:cache会抵抗无效请求,将无效的请求过滤掉,实际进入到后台的量不大。cache记录红包个数,原子操作进行个数递减,到0表示被抢光。财付通按照20万笔每秒入账准备,但实际还不到8万每秒。

通如何保持8w每秒的写入?

答:多主sharding,水平扩展机器。

数据容量多少?

答:一个红包只占一条记录,有效期只有几天,因此不需要太多空间。

查询红包分配,压力大不?

答:抢到红包的人数和红包都在一条cache记录上,没有太大的查询压力。

一个红包一个队列?

答:没有队列,一个红包一条数据,数据上有一个计数器字段。

有没有从数据上证明每个红包的概率是不是均等?

答:不是绝对均等,就是一个简单的拍脑袋算法。

拍脑袋算法,会不会出现两个最佳?

答:会出现金额一样的,但是手气最佳只有一个,先抢到的那个最佳。

每领一个红包就更新数据么?

答:每抢到一个红包,就cas更新剩余金额和红包个数。

红包如何入库入账?

数据库会累加已经领取的个数与金额,插入一条领取记录。入账则是后台异步操作。

入帐出错怎么办?比如红包个数没了,但余额还有?

答:最后会有一个take all操作。另外还有一个对账来保障。

下面这张图是@周帆 同学的杰作!

命令行推送Jar包到nexus

1
mvn deploy:deploy-file -DgroupId=com.tencent -DartifactId=xinge -Dversion=1.1.8 -Dpackaging=jar -DrepositoryId=nexus -Dfile=/Users/gaoyoubo/xinge-push.jar -Durl=http://xxx.xxx.com:8081/nexus/content/repositories/thirdparty/ -DgeneratePom=false

并发队列-无界阻塞延迟队列DelayQueue原理探究

1
2
转载自:http://ifeve.com/%E5%B9%B6%E5%8F%91%E9%98%9F%E5%88%97-%E6%97%A0%E7%95%8C%E9%98%BB%E5%A1%9E%E5%BB%B6%E8%BF%9F%E9%98%9F%E5%88%97delayqueue%E5%8E%9F%E7%90%86%E6%8E%A2%E7%A9%B6/
最近在开发中正好有类似场景。

前言

DelayQueue队列中每个元素都有个过期时间,并且队列是个优先级队列,当从队列获取元素时候,只有过期元素才会出队列。

DelayQueue类图结构

如图DelayQueue中内部使用的是PriorityQueue存放数据,使用ReentrantLock实现线程同步,可知是阻塞队列。另外队列里面的元素要实现Delayed接口,一个是获取当前剩余时间的接口,一个是元素比较的接口,因为这个是有优先级的队列。

offer操作

插入元素到队列,主要插入元素要实现Delayed接口。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public boolean offer(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
q.offer(e);
if (q.peek() == e) {(2
leader = null;
available.signal();
}
return true;
} finally {
lock.unlock();
}
}

首先获取独占锁,然后添加元素到优先级队列,由于q是优先级队列,所以添加元素后,peek并不一定是当前添加的元素,如果(2)为true,说明当前元素e的优先级最小也就即将过期的,这时候激活avaliable变量条件队列里面的线程,通知他们队列里面有元素了。

take操作

获取并移除队列首元素,如果队列没有过期元素则等待。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
for (;;) {
//获取但不移除队首元素(1)
E first = q.peek();
if (first == null)
available.await();//(2)
else {
long delay = first.getDelay(TimeUnit.NANOSECONDS);
if (delay <= 0)//(3)
return q.poll();
else if (leader != null)//(4)
available.await();
else {
Thread thisThread = Thread.currentThread();
leader = thisThread;//(5)
try {
available.awaitNanos(delay);
} finally {
if (leader == thisThread)
leader = null;
}
}
}
}
} finally {
if (leader == null && q.peek() != null)//(6)
available.signal();
lock.unlock();
}
}

第一次调用take时候由于队列空,所以调用(2)把当前线程放入available的条件队列等待,当执行offer并且添加的元素就是队首元素时候就会通知最先等待的线程激活,循环重新获取队首元素,这时候first假如不空,则调用getdelay方法看该元素海剩下多少时间就过期了,如果delay<=0则说明已经过期,则直接出队返回。否者看leader是否为null,不为null则说明是其他线程也在执行take则把该线程放入条件队列,否者是当前线程执行的take方法,则调用(5)await直到剩余过期时间到(这期间该线程会释放锁,所以其他线程可以offer添加元素,也可以take阻塞自己),剩余过期时间到后,该线程会重新竞争得到锁,重新进入循环。

(6)说明当前take返回了元素,如果当前队列还有元素则调用singal激活条件队列里面可能有的等待线程。leader那么为null,那么是第一次调用take获取过期元素的线程,第一次调用的线程调用设置等待时间的await方法等待数据过期,后面调用take的线程则调用await直到signal。

poll操作

获取并移除队头过期元素,否者返回null

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public E poll() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
E first = q.peek();
//如果队列为空,或者不为空但是队头元素没有过期则返回null
if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0)
return null;
else
return q.poll();
} finally {
lock.unlock();
}
}

一个例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class DelayedEle implements Delayed {

private final long delayTime; //延迟时间
private final long expire; //到期时间
private String data; //数据

public DelayedEle(long delay, String data) {
delayTime = delay;
this.data = data;
expire = System.currentTimeMillis() + delay;
}

/**
* 剩余时间=到期时间-当前时间
*/
@Override
public long getDelay(TimeUnit unit) {
return unit.convert(this.expire - System.currentTimeMillis() , TimeUnit.MILLISECONDS);
}

/**
* 优先队列里面优先级规则
*/
@Override
public int compareTo(Delayed o) {
return (int) (this.getDelay(TimeUnit.MILLISECONDS) -o.getDelay(TimeUnit.MILLISECONDS));
}

@Override
public String toString() {
final StringBuilder sb = new StringBuilder("DelayedElement{");
sb.append("delay=").append(delayTime);
sb.append(", expire=").append(expire);
sb.append(", data='").append(data).append('\'');
sb.append('}');
return sb.toString();
}
}

public static void main(String[] args) {
DelayQueue<DelayedEle> delayQueue = new DelayQueue<DelayedEle>();

DelayedEle element1 = new DelayedEle(1000,"zlx");
DelayedEle element2 = new DelayedEle(1000,"gh");

delayQueue.offer(element1);
delayQueue.offer(element2);

element1 = delayQueue.take();
System.out.println(element1);
}

使用场景

TimerQueue的内部实现
ScheduledThreadPoolExecutor中DelayedWorkQueue是对其的优化使用

Git修改默认编辑器为VIM

重做系统了,新安装的Git默认编辑器为nano,各种不习惯,可以通过一下方式将默认编辑器修改为Vim

1
git config --global core.editor vim

maven打包可执行jar文件

需要打包有依赖第三方jar包的可执行jar会用到,他会帮你将所有的第三方的jar包都打到同一个jar中,这样就不用手动去设置classpath

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>cn.mucang.saturn.transfer.Transfer</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>

一篇文章看懂when.js

最近在拾起很久都没做过的前端,总结下When.js的最常用的场景。

场景1

执行异步function a,当成功时执行function b,失败时执行function c,执行过程中需要回调function d来监控执行状态。

这个是最通用的用法,也是when.js中最长用到的,示例代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function a () {
var deferred = when.defer()

for (var i = 0; i < 100; i++) {
try {
deferred.notify(i++);
} catch (err) {
deferred.reject(e)
}
}

deferred.resolve('成功消息')

return deferred.promise;
}

a().then(function b(msg){
console.log('执行成功')
}, function c(err){
console.log('执行失败')
}, function d(i){
console.log('执行中...' + i)
})

总结:then有三个参数,分别是onFulfilled、onRejected、onProgress,通过这三个参数,就可以指定上一个任务在resolve、reject和notify时该如何处理。例如上一个任务被resolve(data),onFulfilled函数就会被触发,data作为它的参数;被reject(reason),那么onRejected就会被触发,收到reason。任何时候,onFulfilled和onRejected都只有其一可以被触发,并且只触发一次;onProgress顾名思义,每次notify时都会被调用。

场景2

执行完function a,再执行function b;执行完function b,在执行function c。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function a () {
var deferred = when.defer()

for (var i = 0; i < 100; i++) {
try {
deferred.notify(i++);
} catch (err) {
deferred.reject(e)
}
}

deferred.resolve('成功消息')

return deferred.promise;
}

a().then(function b(){}).then(function c(){})

nginx-clojure安装使用

安装配置

环境要求

jdk1.6+
nginx1.4+

安装

下载nginx和nginx-clojure源码,分别去他们的官网下载就可以,然后将他们解压、编译、安装。编译安装nginx时,加上nginx-clojure模块,具体安装脚本如下:

1
2
3
./configure --prefix=/usr/local/nginx --add-module=nginx-clojure模块解压路径
make
sudo make install

配置

### 建议这里查看官方文档,比较详细
### 官方文档地址:http://nginx-clojure.github.io/configuration.html#21-jvm-path--class-path--other-jvm-options
jvm_path auto;
# classpath:需要加载nginx-clojure自己的jar包,并加载自己开发的jar包
jvm_classpath "/usr/local/nginx/libs/nginx-clojure-0.4.4/jars/*:/Users/gaoyoubo/work/dianping-service/dianping-nginx/target/dianping-nginx-2.0.1-SNAPSHOT.jar";

使用

rewrite handler

rewrite handler可用于请求的转发。

Java handler类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package my.test;

import static nginx.clojure.java.Constants.*;

public static class MyRewriteProxyPassHandler implements NginxJavaRingHandler {
@Override
public Object[] invoke(Map<String, Object> req) {
String myhost = computeMyHost(req);
((NginxJavaRequest)req).setNGXVariable("myhost", myhost);
return PHASE_DONE;
}

private String computeMyHost(Map<String, Object> req) {
//compute a upstream name or host name;
}
}

nginx.conf配置

set $myhost "";
location /myproxy {
    ### 这里指定handle_type
    rewrite_handler_type 'java';
    ### 这里指定处理类
    rewrite_handler_name 'my.test.MyRewriteProxyPassHandler';
    proxy_pass $myhost;
} 

access handler

可做请求的权限校验

Java handler类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* This is an example of HTTP basic Authentication.
* It will require visitor to input a user name (xfeep) and password (hello!)
* otherwise it will return 401 Unauthorized or BAD USER & PASSWORD
*/
public class BasicAuthHandler implements NginxJavaRingHandler {

@Override
public Object[] invoke(Map<String, Object> request) {
String auth = (String) ((Map)request.get(HEADERS)).get("authorization");
if (auth == null) {
return new Object[] { 401, ArrayMap.create("www-authenticate", "Basic realm=\"Secure Area\""),
"<HTML><BODY><H1>401 Unauthorized.</H1></BODY></HTML>" };
}
String[] up = new String(DatatypeConverter.parseBase64Binary(auth.substring("Basic ".length())), DEFAULT_ENCODING).split(":");
if (up[0].equals("xfeep") && up[1].equals("hello!")) {
return PHASE_DONE;
}
return new Object[] { 401, ArrayMap.create("www-authenticate", "Basic realm=\"Secure Area\""),
"<HTML><BODY><H1>401 Unauthorized BAD USER & PASSWORD.</H1></BODY></HTML>" };
}
}

nginx.conf配置

location /basicAuth {
    access_handler_type 'java';
    access_handler_name 'my.BasicAuthHandler';
    ....
}

header filter

可拦截头信息,并作出相应的处理

Java handler类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package my;

import nginx.clojure.java.NginxJavaRingHandler;
import nginx.clojure.java.Constants;

public class RemoveAndAddMoreHeaders implements NginxJavaHeaderFilter {
@Override
public Object[] doFilter(int status, Map<String, Object> request, Map<String, Object> responseHeaders) {
responseHeaders.remove("Content-Type");
responseHeaders.put("Content-Type", "text/html");
responseHeaders.put("Xfeep-Header", "Hello2!");
responseHeaders.put("Server", "My-Test-Server");
return Constants.PHASE_DONE;
}
}

nginx.conf配置

location /javafilter {
    header_filter_type 'java';
    header_filter_name 'my.RemoveAndAddMoreHeaders ';
    ..................
}

body filter

可修改返回数据

Java handler类

1
2
3
4
5
6
7
8
9
10
public static class StringFacedUppercaseBodyFilter extends StringFacedJavaBodyFilter {
@Override
protected Object[] doFilter(Map<String, Object> request, String body, boolean isLast) throws IOException {
if (isLast) {
return new Object[] {200, null, body.toUpperCase()};
}else {
return new Object[] {null, null, body.toUpperCase()};
}
}
}

nginx.conf配置

location /hello {
  body_filter_type java;
  body_filter_name mytest.StringFacedUppercaseBodyFilter;
}

更多使用场景

nginx-clojure能够获取和修改请求数据、响应数据、header信息等(基本上java servlet中能够获取和修改的数据,他也都能获取和修改),所以基于他,我们能够完成很多servlet能够完成的数据,甚至他能够连接mysql,redis等。

可操作的请求数据

Server port
Server-name
Remote addr
Uri
Query String
Scheme
Request-method
Protocol
Content type
Content length
Character encoding
Headers
Body 

可操作的相应数据

Status
Headers
Body 

使用nginx-clojure配置nginx负载均衡

使用背景

最近遇到一个很困扰的问题,系统请求量变大了一台服务器已经扛不住了。于是我基于mq升级了我的服务,让我的服务能够支持横向扩展,通过mq服务完成各节点之间的通信。于是我们将服务部署到两个节点上,然后通过nginx随机将请求平均分发到两个节点。那么问题来了,在随机分发到两个节点之后服务器的CPU占用有所下降,但是内存占用却没有降下来。于是我们分析了一下原因,因为是随机分发,那么同一条数据请求两台服务器都会随机到,那么在这两台服务器上就会有相同的数据缓存,那么这样就会造成内存的浪费。于是我们就想办法根据请求的参数进行分发,保证同一条数据请求只会到同一台服务器。
开始时我们用到了consistent_hash,但是我们客户端请求不规范有有些参数是放在POST请求中的,consistent_hash是无法根据POST请求中的参数进行hash,然后分发。于是在网上搜索了很多资料,直到我找到了nginx-clojure。选nginx-clojure是因为他可以用我熟悉的语言写插件:Java。
安装配置

安装nginx-clojure插件

下载nginx和nginx-clojure源码,分别去他们的官网下载就可以,然后将他们解压、编译、安装。脚本如下:

1
2
3
./configure --prefix=/usr/local/nginx --add-module=nginx-clojure安装模块
make
sudo make install

配置nginx-clojure

在nginx.conf中

1
2
3
4
5
### 建议这里查看官方文档,比较详细
### 官方文档地址:http://nginx-clojure.github.io/configuration.html#21-jvm-path--class-path--other-jvm-options
jvm_path auto;
# 这个是classpath需要用到的jar包都需要加入到classpath中。
jvm_classpath "/usr/local/nginx/libs/nginx-clojure-0.4.4/jars/*:/Users/gaoyoubo/work/dianping-service/dianping-nginx/target/dianping-nginx-2.0.1-SNAPSHOT.jar";

配置自己的location

1
2
3
4
5
6
7
8
9
10
11
12
13
set $node "";
location / {
# 加上他会读取POST请求数据,不需要的时候建议关掉
always_read_body on;
# handler类型,nginx-clojure支持三种:clojure、groovy、java,这里主要讲解java
rewrite_handler_type 'java';
# 这里是处理类
rewrite_handler_name 'cn.mucang.dianping.nginx.DianpingRewriteHandler';
proxy_pass $node;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

编写处理类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package cn.mucang.dianping.nginx;

import nginx.clojure.NativeInputStream;
import nginx.clojure.NginxClojureRT;
import nginx.clojure.java.Constants;
import nginx.clojure.java.NginxJavaRequest;
import nginx.clojure.java.NginxJavaRingHandler;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
* @author Gao Youbo
* @since 2016-03-17 15:02
*/
public class DianpingRewriteHandler implements NginxJavaRingHandler {
public static final String KEY_URI = "uri";
public static final String KEY_BODY = "body";
public static final String KEY_REQUEST_METHOD = "request-method";
public static final String KEY_QUERY_STRING = "query-string";
public static final String ENCODING = "UTF-8";

public static final Map NODES = new HashMap();
public static final int NODE_SIZE = 2;
public static final String MASTER_NODE = "node1";
public static final String SALVE_NODE = "node2";

private static final Random R = new Random();

static {
NODES.put(0, MASTER_NODE);
NODES.put(1, SALVE_NODE);
}

public Object[] invoke(Map requestMap) throws IOException {
long start = System.currentTimeMillis();
Map params = getParams(requestMap); // 所有的请求参数包括GET和POST
String node = getNode(requestMap);

NginxJavaRequest request = (NginxJavaRequest) requestMap;
request.setVariable("node", normalizeNode(node));

long elasped = System.currentTimeMillis() - start;
NginxClojureRT.log.info(String.format("[gaoyoubo] elasped:%s ms, node=%s, uri:%s, elasped, node, uri));

return Constants.PHASE_DONE;
}

/**
* 计算当前请求应该走哪个节点
*
* @param requestMap
* @return
*/
private String getNode(Map requestMap) {
// 业务逻辑
}

private String normalizeNode(String node) {
return "http://" + node;
}

/**
* 获取请求参数, 包括GET和POST
*
* @param requestMap
* @return
*/
private Map getParams(Map requestMap) {
Map params = new HashMap<>();
try {
params.putAll(getGetParams(requestMap));
params.putAll(getPostParams(requestMap));
} catch (Exception e) {
NginxClojureRT.log.error("获取请求参数失败", e);
}
return params;
}

/**
* 获取GET请求参数
*
* @param requestMap
* @return
*/
private Map getGetParams(Map requestMap) {
String queryString = MapUtils.getString(requestMap, KEY_QUERY_STRING);
return buildQuerys(queryString);
}

/**
* 获取POST请求参数
*
* @param requestMap
* @return
*/
private Map getPostParams(Map requestMap) throws IOException {
String requestMethod = MapUtils.getString(requestMap, KEY_REQUEST_METHOD);
if (StringUtils.equalsIgnoreCase(requestMethod, "POST")) { // 如果是POST请求,那么处理下POST参数
Object bodyObj = requestMap.get(KEY_BODY);
if (bodyObj != null) {
NativeInputStream nis = (NativeInputStream) bodyObj;
String body = IOUtils.toString(nis, ENCODING);
return buildQuerys(body);
}
}
return new HashMap<>();
}

/**
* 将字符串格式的参数转换成Map
*
* @param queryString
* @return
*/
private Map buildQuerys(String queryString) {
Map params = new HashMap<>();
if (StringUtils.isBlank(queryString)) {
return params;
}
String[] kvs = queryString.split("&");
if (kvs != null) {
for (String kv : kvs) {
String[] pair = kv.split("\\=", 2);
if (pair.length == 2) {
params.put(pair[0], urlDecode(pair[1], ENCODING));
}
}
}
return params;
}

private String urlDecode(String s, String encoding) {
try {
return URLDecoder.decode(s, encoding);
} catch (Exception ex) {
NginxClojureRT.log.error(null, ex);
}
return s;
}
}

生产环境下JAVA进程高CPU占用故障排查

收藏一篇文章,这两天被驾校之家CPU占用过高的问题弄的寝食难安。马上用下面的方法监控一下。

参考文章:

    1. http://blog.csdn.net/blade2001/article/details/9065985

    2. http://blog.csdn.net/jiangguilong2000/article/details/17971247

问题描述:
生产环境下的某台tomcat7服务器,在刚发布时的时候一切都很正常,在运行一段时间后就出现CPU占用很高的问题,基本上是负载一天比一天高。

问题分析:
1,程序属于CPU密集型,和开发沟通过,排除此类情况。
2,程序代码有问题,出现死循环,可能性极大。

问题解决:
1,开发那边无法排查代码某个模块有问题,从日志上也无法分析得出。
2,记得原来通过strace跟踪的方法解决了一台PHP服务器CPU占用高的问题,但是通过这种方法无效,经过google搜索,发现可以通过下面的方法进行解决,那就尝试下吧。

解决过程:
1,根据top命令,发现PID为2633的Java进程占用CPU高达300%,出现故障。

2,找到该进程后,如何定位具体线程或代码呢,首先显示线程列表,并按照CPU占用高的线程排序:
[root@localhost logs]# ps -mp 2633 -o THREAD,tid,time | sort -rn

显示结果如下:
USER     %CPU PRI SCNT WCHAN  USER SYSTEM   TID     TIME
root     10.5  19    - -         -      -  3626 00:12:48
root     10.1  19    - -         -      -  3593 00:12:16

找到了耗时最高的线程3626,占用CPU时间有12分钟了!

将需要的线程ID转换为16进制格式:
[root@localhost logs]# printf “%x\n” 3626
e18

最后打印线程的堆栈信息:
[root@localhost logs]# jstack 2633 |grep e18 -A 30

将输出的信息发给开发部进行确认,这样就能找出有问题的代码。
通过最近几天的监控,CPU已经安静下来了。

FULL GC分析过程分享

转载-原文地址:http://www.taobaotest.com/blogs/2294

在性能测试过程中,FULL GC频繁是比较常见的问题,FULL GC 产生的原因有很多,这里主要针对meta压测过程中分析FULL GC问题的一些思路进行分享,供大家参考

1.如何发现是否发生FULL GC和FULL GC是否频繁

使用JDK自带的轻量级小工具jstat

     语法结构:

Usage: jstat -help|-options

             jstat -

 参数解释:

Options — 选项,我们一般使用 -gcutil 查看gc情况

vmid    — VM的进程号,即当前运行的java进程号

interval– 间隔时间,单位为秒或者毫秒

count   — 打印次数,如果缺省则打印无数次

比如 /opt/taobao/java/bin/jstat –gcutil pid 5000

 

输出结果:

        S0        S1         E          O          P        YGC      YGCT        FGC     FGCT        GCT

           0.00  90.63 100.00  58.82   3.51    183    2.059     0    0.000    2.059

    0.00  15.48   7.80  60.99   3.51    185    2.092     1    0.305    2.397

    0.00  15.48  18.10  47.90   3.51    185    2.092     2    0.348    2.440

 S0  — Heap上的 Survivor space 0 区已使用空间的百分比
 S1  — Heap上的 Survivor space 1 区已使用空间的百分比
 E   — Heap上的 Eden space 区已使用空间的百分比
 O   — Heap上的 Old space 区已使用空间的百分比
 P   — Perm space 区已使用空间的百分比
 YGC — 从应用程序启动到采样时发生 Young GC 的次数
 YGCT– 从应用程序启动到采样时 Young GC 所用的时间(单位秒)
 FGC — 从应用程序启动到采样时发生 Full GC 的次数
 FGCT– 从应用程序启动到采样时 Full GC 所用的时间(单位秒)
 GCT — 从应用程序启动到采样时用于垃圾回收的总时间(单位秒)

    通过FGC我们可以发现系统是否发生FULL GC和FULL GC的频率

2.  FULL GC分析和问题定位

    a.     GC log收集和分析

(1)在JVM启动参数增加:”-verbose:gc -Xloggc:<file_name>  -XX:+PrintGCDetails -XX:+PrintGCDateStamps”

    PrintGCTimeStamp只能获得相对时间,建议使用PrintGCDateStamps获得full gc 发生的绝对时间

      (2)如果采用CMS GC,仔细分析jstat FGC输出和GC 日志会发现, CMS的每个并发GC周期则有两个stop-the-world阶段——initial mark与final re-mark使得CMS的每个并发GC周期总共会更新full GC计数器两次,initial mark与final re-mark各一次

    

    b.     Dump JVM 内存快照

/opt/taobao/java/bin/jmap -dump:format=b,file=dump.bin pid

这里有一个问题是什么时候进行dump?

一种方法是前面提到的用jstat工具观察,当OLD区到达比较高的比例如60%,一般会很快触发一次FULL GC,可以进行一次DUMP,在FULL GC发生以后再DUMP一次,这样比较就可以发现到底是哪些对象导致不停的FULL GC

另外一种方法是通过配置JVM参数

 -XX:+HeapDumpBeforeFullGC -XX:+HeapDumpAfterFullGC分别用于指定在full GC之前与之后生成heap dump 

    c.     利用MAT((Memory Analyzer Tool)工具分析dump文件

关于MAT具体使用方法网上有很多介绍,这里不做详细展开,这里需要注意的是:

(1)   MAT缺省只分析reachable的对象,unreachable的对象(将被收集掉的对象)被忽略,而分析FULL GC频繁原因时unreachable object也应该同时被重点关注。如果要显示unreachable的对象细节必须用mat 1.1以上版本并且打开选项“keep unreachable object”

(2)   通常dump文件会好几个G,无法在windows上直接进行分析,我们可以先把dump文件在linux上进行分析,再把分析好的文件拷贝到windows上,在windows上用MAT打开分析文件。

下面是Meta2.0压测曾遇到的FULL GC频繁问题的分析结果,比较明显,DispatchRequest对象有4千多万个,一共超过2G,并最终导致OOM

83f48d2a9de38682ed93018f08211d9e_detail