1. 程式人生 > >golang redis 佇列刪除圖片

golang redis 佇列刪除圖片

 之前幾篇完成了縮圖功能,今天在常帥的指導下,完成了golang操作佇列刪除圖片功能,之前打算用lua-resty-redis弄,尼瑪,不懂怎麼觸發,SB了。然後常帥說用Golang,好吧.就有了下面的程式碼。

package main
import (
	"fmt"
	"time"
	"gopkg.in/redis.v5"
	"strings"
	"os"
	"path/filepath"
)
var client *redis.Client
func main() {
	fmt.Println("Hello, 世界")
	client = redis.NewClient(&redis.Options{
		Addr:         "ip:6379",
		DialTimeout:  10 * time.Second,
		ReadTimeout:  30 * time.Second,
		WriteTimeout: 30 * time.Second,
		PoolSize:     10,
		PoolTimeout:  30 * time.Second,
	})
	pong, err := client.Ping().Result()
	fmt.Println(pong,err)
	if err != nil {
		panic(err)
	}
	for{
		result, err := client.BLPop(0, "sync_img").Result()
		if err != nil {
			fmt.Println("error:  %s",err)
			continue
		}
		img_path := result[1]
		if len(img_path) < 1 {
			fmt.Println(" path is   null")
			continue
		}
		if(strings.Contains(img_path,"..")){
			fmt.Println(" path can't contains ..")
			continue
		}
		// (gif|jpg|png|jpeg
		if(strings.HasSuffix(img_path, ".gif")  || strings.HasSuffix(img_path, ".jpg")  || strings.HasSuffix(img_path, ".png")  || strings.HasSuffix(img_path, ".jpeg")  ){
			full_path                 := "/tmp"+img_path
			files, err		  := filepath.Glob(full_path+"*")
			if err != nil{
				fmt.Println(err)
				continue
			}
			for _, f := range files{
				fmt.Println("rm path :%s",f)
				removeErr :=os.Remove(f)
				if removeErr != nil {
				        fmt.Printf("file remove Error! %s", removeErr)
				} else {
				        //如果刪除成功則輸出 file remove OK!
				        fmt.Print("file remove OK!")
				 }
			}
			
		}else{
			fmt.Println(" only receive : gif | jpg |png |jpeg  ")
		}
	}
}



上面的程式碼東拼西湊的,對了,需要先用Go安裝: go get gopkg.in/redis.v5

然後在控制檯執行執行命令: go run xxx.go  

然後常帥說在伺服器上使用root執行許可權太大了,一不小心把刪掉別的資料怎麼辦,然後找到使用nobody執行命令,修改如下

vim /etc/passwd
	找到
	nobody:x:99:99:Nobody:/:/sbin/nologin
	改為nobody:x:99:99:Nobody:/:/bin/bash
	後儲存執行su -nobody

  接著就可以執行: su -m nobody -c "go run redis_queue.go &"  

  資源: https://github.com/go-redis/redis 打完收工