go语言写web感觉还是没有django写web那么得心应手,不过利用go的goroute做一些小组件还是很不错的。
django如果需要执行异步任务的话,可以将任务存入Redis队列,然后通过Go写的程序从Redis队列中取出任务,异步执行。比如发送邮件。
做了下简单测试,以下代码是能够实现通信的:
python端:
import redis,json
pool=redis.ConnectionPool(host='127.0.0.1',port=6379,db=0)
r = redis.StrictRedis(connection_pool=pool)
msg={}
msg["to"]="xxxxxx@qq.com"
msg['subject']="hello msg from redis"
msg['body']="body msg from redis"
print(r.lpush('email', msg))
print(r.llen('email'))
Go端:
package main
import (
"fmt"
"github.com/astaxie/beego/logs"
"github.com/garyburd/redigo/redis"
"time"
)
var RedisPool *redis.Pool
var conn redis.Conn
func initRedis() (err error) {
RedisPool = &redis.Pool{
MaxIdle: 8,
MaxActive: 64,
IdleTimeout: 300 * time.Second,
Dial: func() (redis.Conn, error) {
return redis.Dial("tcp", "127.0.0.1:6379")
},
}
conn = RedisPool.Get()
//defer conn.Close()
_, err = conn.Do("ping")
if err != nil {
logs.Error("ping redis failed, err:%v", err)
return
}
return
}
func main() {
initRedis()
defer conn.Close()
for {
reply, _ := conn.Do("LPOP", "email")
if reply != nil {
fmt.Println(string(reply.([]byte)))
}else{
time.Sleep(time.Second * 2)
fmt.Println("wait 2 seconds")
}
}
}
go程序中,获取到发送邮件的to,body,subtitle,就能去实现具体发送业务了。