javasgl

step by step


  • Home

  • Archives

  • Tags

  • Categories

  • About

  • Search

python 多进程、多线程简单使用

Posted on 2018-03-07 | In python | Visitors

python 中可以使用 multiprocessing (多进程) 和 multiprocessing.dummy(多线程) 来实现并发操作。
两者在使用方式上一样,只不过实现并发的方式不同。

以下简单使用案例以 multiprocessing.dummy 多线程为例:

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

from multiprocessing.dummy import Pool

def compute(param):
return param*100

params = [ _ for _ in range(10) ]

pool = Pool()

results = pool.map(compute, params)

pool.close()

pool.join()

print(results)

注意:多进程(multiprocessing) 无法在 celery 等后台进程中使用,因为 celery 等后台进程不再允许生成子进程,这时候就只能使用多线程或者协程了。

1
daemonic processes are not allowed to have children

go build 常见编译优化

Posted on 2018-02-27 | In go | Visitors

一般情况下,go build 可以直接编译程序,无需额外的参数设定。
但在编译生产环境下使用的可执行程序时候,go build 的一些参数还是很有用的。

减小编译后可执行程序的大小

1
go build -ldflags '-w -s'

说明:
-w 禁止生成debug信息,注意使用该选项后,无法使用 gdb 进行调试
-s 禁用符号表
可以使用 go tool link --help 查看 ldflags 各参数含义

禁止gc优化和内联

1
go build -gcflags '-N -l'

说明:
-N 禁止编译优化
-l 禁止内联,禁止内联也可以一定程度上减小可执行程序大小
可以使用 go tool compile --help 查看 gcflags 各参数含义

golang同时监听TCP、HTTP端口提供服务

Posted on 2018-02-24 | In go | Visitors

之前一个golang写的服务,是使用 TCP 方式进行通信的,但是并没很好的处理粘包问题(其实是根本就没有处理粘包问题)。项目需要添加新功能后迅速上线,所以准备先采用http来通信,避免粘包问题。

项目入口 main.go 中,之前是监听 TCP 连接,代码大致如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func main(){
server,err:= net.Listen("tcp","host:port")
if err!=nil{
return
}
defer server.Close()

for{
conn,err:= server.Accept()
if err!=nil{
continue
}
go handleConn(conn)
}
}

func handleConn(conn net.Conn){
//do somethings
}

现在需要在此基础之上监听 http 连接,由于 http.ListenAndServe() 方法是阻塞的,所以需要新开goroutine进行监听,代码示意如下:

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

http.HandleFunc("/hi", Router)
//因为会阻塞,所以需要新开goroutine进行监听
go http.ListenAndServe("host:http_port", nil)

server,err:= net.Listen("tcp","host:tcp_port")
if err!=nil{
return
}
defer server.Close()

for{
conn,err:= server.Accept()
if err!=nil{
continue
}
go handleConn(conn)
}
}

func handleConn(conn net.Conn){
//do somethings
}

使用 Elasticsearch alias 功能切换 index

Posted on 2017-12-20 | In elasticsearch | Visitors

有时候,需要将已有的索引做些调整重建为另外一个索引,但是为了不影响线上的访问,需要无缝切换到新的索引上。

基本上有两种方案,一是改代码,使线上代码访问新的索引,二是使用 alias 别名功能。

第一种方案有弊端,在代码进行发布到具体机器之前的并不能保证所有的访问都是访问的新的索引。

这里选择通过 alias 来切换索引,因为 alias 中的多条命令是原子性。

Read more »

python celery 强制使用root用户执行

Posted on 2017-12-19 | In python | Visitors

当 celery 使用 root 用户执行时,会报出如下警告:

1
RuntimeWarning: You're running the worker with superuser privileges: this is absolutely not recommended!

低版本的 celery 情况不清楚,但是 celery 4.1.0 版本中,这个警告是无法去除的。因为源码中是这样写的:

Read more »
1…345…12
javasgl

javasgl

A journey of a thousand miles begins with single step

60 posts
13 categories
94 tags
RSS
GitHub Wechat
© 2020 javasgl
Powered by Hexo
Theme - NexT.Mist
0%