golang优雅退出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
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
package main
import (
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
func worker(jobs <-chan int) {
for job := range jobs {
fmt.Println(job)
time.Sleep(500 * time.Millisecond)
}
}
func main() {
jobs := make(chan int, 1000)
var wg sync.WaitGroup
// Spawn example workers
for i := 0; i < 3; i++ {
wg.Add(1)
go func(jobs <-chan int) {
defer wg.Done()
worker(jobs)
fmt.Println("Worker is done.")
}(jobs)
}
// Create example messages
for i := 0; i < 100; i++ {
jobs <- i
}
waitForSignal()
close(jobs)
fmt.Println("Closed jobs!")
wg.Wait()
}
func waitForSignal() {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt)
signal.Notify(sigs, syscall.SIGTERM)
<-sigs
}

阅读更多

golang限制goroutine数量

Refer:https://github.com/evilsocket/brutemachine

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
package main
import (
"sync"
"fmt"
"strconv"
"time"
//"runtime"
)
var wait sync.WaitGroup
var input = make(chan string)
func inputConsumer() {
for in := range input {
fmt.Println(in)
if in=="2" {
for i:=1; i<10 ;i++{
wait.Add(1)
input <- "hello"
}
}
//println(runtime.NumGoroutine(),"===")
time.Sleep(time.Second)
wait.Done()
}
}
func main() {
//控制goroutine数量为10个
for i := 0; i <10; i++ {
go inputConsumer()
}
for j:=1 ;j<20;j++ {
wait.Add(1)
input <- strconv.Itoa(j)
}
wait.Wait()
}

阅读更多

golang生产者消费者模型

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
package main
import "time"
import (
"fmt"
"math/rand"
"strconv"
)
func main() {
c1 := make(chan string, 10)
flag := make (chan bool)
count := 0
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for j := 1; j < 6; j++ {
go func() {
for i := 1; i < 10; i++ {
fmt.Println(rand.Intn(10))
time.Sleep(time.Duration(rand.Intn(10)) * time.Second)
c1 <- strconv.Itoa(i) + "--result 1"
}
}()
}
for j := 1; j < 6; j++ {
go func() {
for {
select {
case res := <-c1:
fmt.Println(res)
case <-ticker.C:
count = count + 1
fmt.Println("timeout 1")
}
if count > 10 {
flag <- true
break
}
}
}()
}
<- flag
}

阅读更多

为什么要使用反射机制

反射的目的就是为了扩展未知的应用.
比如你写了一个程序,这个程序定义了一些接口,只要实现了这些接口的dll都可以作为插件来插入到这个程序中。那么怎么实现呢?就可以通过反射来实现。就是把dll加载进内存,然后通过反射的方式来调用dll中的方法,很多工厂模式就是使用的反射。

log4j读取配置文件,通过反射机制动态的加载类.

阅读更多

Spring 自定义404

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
package com.example.Controller;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class AppErrorController implements ErrorController {
private final static String ERROR_PATH = "/error";
@ResponseBody
@RequestMapping(value = ERROR_PATH)
public String errorHtml() {
return "页面不存在";
}
@Override
public String getErrorPath() {
return ERROR_PATH;
}
}

阅读更多

python多线程返回结果

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
import threading,time
# sum=[]
lock = threading.Lock()
from Queue import Queue
maxs=5 ##并发的线程数量
threadLimiter=threading.BoundedSemaphore(maxs)
class test(threading.Thread):
def __init__(self,q,p):
self.p = p
self.q = q
threading.Thread.__init__(self)
def run(self):
threadLimiter.acquire() #获取
# global sum
# lock.acquire()
# sum.append(self.p)
try:
self.q.put(self.p)
except:
pass
finally:
threadLimiter.release() #释放
# time.sleep(0.5)
# lock.release()
def get_result(self):
return self.q
def tt(x):
queue = Queue()
for i in range(10):
cur=test(queue,x)
cur.start()
for i in range(10):
cur.join()
while cur.isAlive():
continue
out=[]
tmp=cur.get_result()
while not tmp.empty():
out.append(tmp.get())
return out
print tt(11)
print tt(12)

阅读更多

前端树形控件

前端树形控件

阅读更多

Python之函数Hook

py2.7测试通过

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
# coding=utf-8
def hook_func(module, func, act, hook_arg, hook_result):
try:
if hook_arg or hook_result:
old_module = __import__(module)
old_function = getattr(old_module, func)
def wrapper(*args, **kwargs):
if hook_arg:
a = list(args)
k = [v for k, v in enumerate(kwargs)]
values = a.extend(k) if k else a
act(values)
result = old_function(*args, **kwargs)
if hook_result:
act(result)
return result
setattr(old_module, func, wrapper)
else:
pass
except Exception,e:
print e
def check_file_path(values):
if any('../' in path for path in values):
raise Exception('Insecure filepath found!')
def monkey_patch():
hook_func('__builtin__', 'open', check_file_path, hook_arg=True, hook_result=False)
if __name__ == '__main__':
monkey_patch()
open(input('enter your path >'),'w+')

阅读更多

Django后台使用富文本编辑器-kindeditor

Django 常用的富文本编辑器有ckeditor,ueditor,kindeditor,tinyme等.

阅读更多

python pickle

Django使用pickle序列化数据存储到数据库是非常方便的,pickle适用于python所有数据类型的序列化,为什么要使用pickle而不使用json.dumps()呢?因为它会自动转义!

models.py

1
2
3
4
class blobtest(models.Model):
data=models.BinaryField()
def __unicode__(self):
return self.data

阅读更多