minio.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. package utils
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "git.getensh.com/common/gopkgs/cache"
  7. "github.com/minio/minio-go/v6"
  8. "io"
  9. "log"
  10. "math/rand"
  11. hurl "net/url"
  12. "property-applete-gateway/parser"
  13. "strconv"
  14. "strings"
  15. "time"
  16. pb_v1 "property-applete-gateway/pb/v1"
  17. "property-applete-gateway/pb"
  18. )
  19. const (
  20. NUmStr = "0123456789"
  21. CharStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  22. SpecStr = "+=-@#~,.[]()!%^*$"
  23. )
  24. func GenerateRandomStr(length int, charset string) string {
  25. time.Sleep(1*time.Microsecond)
  26. rand.Seed(time.Now().UnixNano())
  27. //初始化密码切片
  28. var passwd []byte = make([]byte, length, length)
  29. //源字符串
  30. var sourceStr string
  31. //判断字符类型,如果是数字
  32. if charset == "num" {
  33. sourceStr = NUmStr
  34. //如果选的是字符
  35. } else if charset == "char" {
  36. sourceStr = charset
  37. //如果选的是混合模式
  38. } else if charset == "mix" {
  39. sourceStr = fmt.Sprintf("%s%s", NUmStr, CharStr)
  40. //如果选的是高级模式
  41. } else if charset == "advance" {
  42. sourceStr = fmt.Sprintf("%s%s%s", NUmStr, CharStr, SpecStr)
  43. } else {
  44. sourceStr = fmt.Sprintf("%s%s%s", NUmStr, CharStr, SpecStr)
  45. }
  46. //遍历,生成一个随机index索引,
  47. for i := 0; i < length; i++ {
  48. index := rand.Intn(len(sourceStr))
  49. passwd[i] = sourceStr[index]
  50. }
  51. return string(passwd)
  52. }
  53. func UploadToMinio(fileName string, r io.Reader, size int64, imgMine string) (objName string, err error) {
  54. endpoint := parser.Conf.Oss.Endpoint
  55. accessKeyID := parser.Conf.Oss.Id
  56. secretAccessKey := parser.Conf.Oss.Key
  57. useSSL := false
  58. // Initialize minio client object.
  59. minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL)
  60. if err != nil {
  61. return "", err
  62. }
  63. // Make a new bucket called mymusic.
  64. bucketName := parser.Conf.Oss.PropertyCompanyBucket
  65. contentType := imgMine
  66. objectName := ""
  67. count := 0
  68. exist := false
  69. array := strings.Split(fileName, ".")
  70. tail := ""
  71. if len(array) > 0 {
  72. tail = array[len(array)-1]
  73. }
  74. rkeyPrefix := "oss_obj_exist_"
  75. rkey := ""
  76. defer func() {
  77. if rkey != "" {
  78. cache.RedisUnlock(rkey)
  79. }
  80. }()
  81. for ;count < 10;count++ {
  82. if rkey != "" {
  83. cache.RedisUnlock(rkey)
  84. rkey = ""
  85. }
  86. objectName = fmt.Sprintf("%d####", time.Now().Unix()) + GenerateRandomStr(32, "mix") +"."+tail
  87. // 互斥判断文件是否存在
  88. rkey = rkeyPrefix + objectName
  89. if !cache.RedisLock(rkey) {
  90. time.Sleep(200*time.Millisecond)
  91. rkey = ""
  92. continue
  93. }
  94. exist, err = ObjExist(endpoint, bucketName, objectName)
  95. if err != nil {
  96. return "", err
  97. }
  98. if exist {
  99. continue
  100. }
  101. // Upload the zip file with FPutObject
  102. _, err = minioClient.PutObject(bucketName, objectName, r, size, minio.PutObjectOptions{ContentType:contentType})
  103. if err != nil {
  104. return "", err
  105. }
  106. ret := parser.Conf.Oss.Protocol +"://"+endpoint+"/"+bucketName+"/"+hurl.QueryEscape(objectName)
  107. ObjTaskAdd(ret)
  108. return ret, nil
  109. }
  110. if exist {
  111. return "", errors.New("文件已存在")
  112. }
  113. return "", errors.New("系统繁忙")
  114. }
  115. func parseObjUrl(objUrl string) (string, string, string, string) {
  116. array := strings.Split(objUrl, "://")
  117. protocol, endpoint, bucketName, objName := "", "", "", ""
  118. if len(array) < 2 {
  119. return "", "", "", ""
  120. }
  121. protocol = array[0]
  122. array = strings.Split(array[1], "/")
  123. if len(array) != 3 {
  124. return "", "", "", ""
  125. }
  126. endpoint = array[0]
  127. bucketName = array[1]
  128. objName = array[2]
  129. return protocol, endpoint, bucketName, objName
  130. }
  131. const ObjKey = "applete_minio_obj"
  132. func ObjTaskAdd(objUrl string) {
  133. value := fmt.Sprintf("%s", objUrl)
  134. cache.Redis().SAdd(ObjKey, value)
  135. }
  136. func delNotExist(objUrl string) error {
  137. mreq := pb_v1.OssObjDelNotExistRequest{ObjUrl:objUrl}
  138. _, err := pb.Common.OssObjDelNotExist(context.Background(), &mreq)
  139. fmt.Printf("************:%v,%v\n", objUrl, err)
  140. return err
  141. }
  142. func ObjTaskHandle() {
  143. count := 0
  144. for count < 20 {
  145. count++
  146. objStr, _ := cache.Redis().SPop(ObjKey)
  147. fmt.Printf("************:%s\n", objStr)
  148. if objStr == "" {
  149. break
  150. }
  151. _, _, _, objName := parseObjUrl(objStr)
  152. array := strings.Split(objName, "%23%23%23%23")
  153. if len(array) != 2 {
  154. continue
  155. }
  156. timeStr := array[0]
  157. timestamp, _ := strconv.ParseInt(timeStr, 10, 64)
  158. if false {
  159. if delNotExist(objStr) != nil {
  160. cache.Redis().SAdd(ObjKey, objStr)
  161. }
  162. continue
  163. }
  164. if time.Now().Unix() - timestamp < 600 {
  165. cache.Redis().SAdd(ObjKey, objStr)
  166. time.Sleep(1*time.Second)
  167. continue
  168. }
  169. if delNotExist(objStr) != nil {
  170. cache.Redis().SAdd(ObjKey, objStr)
  171. }
  172. }
  173. }
  174. func ObjTask(ctx context.Context) {
  175. if false {
  176. tmp := ""
  177. fmt.Printf("input:\n")
  178. fmt.Scanln(&tmp)
  179. fmt.Printf("after input\n")
  180. ObjTaskHandle()
  181. }
  182. t := time.NewTicker(600 * time.Second)
  183. for {
  184. select {
  185. case <-t.C:
  186. ObjTaskHandle()
  187. case <-ctx.Done():
  188. return
  189. }
  190. }
  191. }
  192. func ObjExist(endpoint, bucketName, objName string) (bool, error) {
  193. if endpoint == "" {
  194. return false, nil
  195. }
  196. //endpoint := parser.Conf.Oss.Endpoint
  197. accessKeyID := parser.Conf.Oss.Id
  198. secretAccessKey := parser.Conf.Oss.Key
  199. useSSL := false
  200. // Initialize minio client object.
  201. minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL)
  202. if err != nil {
  203. return false, err
  204. }
  205. // Make a new bucket called mymusic.
  206. //bucketName := parser.Conf.Oss.PropertyCompanyBucket
  207. //objName := ""
  208. obj, err := minioClient.GetObject(bucketName, objName, minio.GetObjectOptions{})
  209. if err != nil {
  210. return false, err
  211. }
  212. defer obj.Close()
  213. _, err = obj.Stat()
  214. if err != nil {
  215. if strings.Contains(err.Error(), " not exist") {
  216. return false, nil
  217. }
  218. return false, err
  219. }
  220. return true, nil
  221. }
  222. func RemoveFromMinio(objUrl string) (err error) {
  223. _, endpoint, bucketName, objName := parseObjUrl(objUrl)
  224. if endpoint == "" {
  225. return nil
  226. }
  227. //endpoint := parser.Conf.Oss.Endpoint
  228. accessKeyID := parser.Conf.Oss.Id
  229. secretAccessKey := parser.Conf.Oss.Key
  230. useSSL := false
  231. // Initialize minio client object.
  232. minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL)
  233. if err != nil {
  234. return err
  235. }
  236. // Make a new bucket called mymusic.
  237. //bucketName := parser.Conf.Oss.PropertyCompanyBucket
  238. //objName := ""
  239. err = minioClient.RemoveObject(bucketName, objName)
  240. if err != nil {
  241. return err
  242. }
  243. return nil
  244. }
  245. func GetFilePath(objName string) (string, error) {
  246. endpoint := parser.Conf.Oss.Endpoint
  247. accessKeyID := parser.Conf.Oss.Id
  248. secretAccessKey := parser.Conf.Oss.Key
  249. useSSL := false
  250. // Initialize minio client object.
  251. minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL)
  252. if err != nil {
  253. return "", err
  254. }
  255. // Make a new bucket called mymusic.
  256. bucketName := parser.Conf.Oss.PropertyCompanyBucket
  257. rr, er := minioClient.PresignedGetObject(bucketName, objName, 24*time.Hour, hurl.Values{})
  258. if er != nil {
  259. fmt.Printf("获取文件路径失败:%v\n", er)
  260. return "", er
  261. }
  262. return rr.String(), nil
  263. }
  264. func MiniTest() {
  265. endpoint := "47.108.135.38:9000"
  266. accessKeyID := "minioadmin"
  267. secretAccessKey := "hly@1353406"
  268. useSSL := false
  269. // Initialize minio client object.
  270. minioClient, err := minio.New(endpoint, accessKeyID, secretAccessKey, useSSL)
  271. if err != nil {
  272. log.Fatalln(err)
  273. }
  274. // Make a new bucket called mymusic.
  275. bucketName := "testb"
  276. location := ""
  277. err = minioClient.MakeBucket(bucketName, location)
  278. if err != nil {
  279. // Check to see if we already own this bucket (which happens if you run this twice)
  280. exists, errBucketExists := minioClient.BucketExists(bucketName)
  281. if errBucketExists == nil && exists {
  282. log.Printf("We already own %s\n", bucketName)
  283. } else {
  284. log.Fatalln(err)
  285. }
  286. } else {
  287. log.Printf("Successfully created %s\n", bucketName)
  288. }
  289. // Upload the zip file
  290. objectName := "5.png"
  291. filePath := "D:\\5.png"
  292. contentType := ""
  293. // Upload the zip file with FPutObject
  294. n, err := minioClient.FPutObject(bucketName, objectName, filePath, minio.PutObjectOptions{ContentType:contentType})
  295. if err != nil {
  296. log.Fatalln(err)
  297. }
  298. log.Printf("Successfully uploaded %s of size %d\n", objectName, n)
  299. rr, er := minioClient.PresignedGetObject("testb", objectName, 24 * 365 * 100 *time.Hour, hurl.Values{})
  300. if er != nil {
  301. fmt.Printf("xxxx:%v\n", er)
  302. return
  303. }
  304. fmt.Printf("xxxx:%s\n", rr.String())
  305. }