instance.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. // Package instance provides instances management.
  7. //
  8. // Note that this package is not used for cache, as it has no cache expiration.
  9. package instance
  10. import (
  11. "github.com/gogf/gf/v2/container/gmap"
  12. "github.com/gogf/gf/v2/encoding/ghash"
  13. )
  14. const (
  15. groupNumber = 64
  16. )
  17. var (
  18. groups = make([]*gmap.StrAnyMap, groupNumber)
  19. )
  20. func init() {
  21. for i := 0; i < groupNumber; i++ {
  22. groups[i] = gmap.NewStrAnyMap(true)
  23. }
  24. }
  25. func getGroup(key string) *gmap.StrAnyMap {
  26. return groups[int(ghash.DJB([]byte(key))%groupNumber)]
  27. }
  28. // Get returns the instance by given name.
  29. func Get(name string) interface{} {
  30. return getGroup(name).Get(name)
  31. }
  32. // Set sets an instance to the instance manager with given name.
  33. func Set(name string, instance interface{}) {
  34. getGroup(name).Set(name, instance)
  35. }
  36. // GetOrSet returns the instance by name,
  37. // or set instance to the instance manager if it does not exist and returns this instance.
  38. func GetOrSet(name string, instance interface{}) interface{} {
  39. return getGroup(name).GetOrSet(name, instance)
  40. }
  41. // GetOrSetFunc returns the instance by name,
  42. // or sets instance with returned value of callback function `f` if it does not exist
  43. // and then returns this instance.
  44. func GetOrSetFunc(name string, f func() interface{}) interface{} {
  45. return getGroup(name).GetOrSetFunc(name, f)
  46. }
  47. // GetOrSetFuncLock returns the instance by name,
  48. // or sets instance with returned value of callback function `f` if it does not exist
  49. // and then returns this instance.
  50. //
  51. // GetOrSetFuncLock differs with GetOrSetFunc function is that it executes function `f`
  52. // with mutex.Lock of the hash map.
  53. func GetOrSetFuncLock(name string, f func() interface{}) interface{} {
  54. return getGroup(name).GetOrSetFuncLock(name, f)
  55. }
  56. // SetIfNotExist sets `instance` to the map if the `name` does not exist, then returns true.
  57. // It returns false if `name` exists, and `instance` would be ignored.
  58. func SetIfNotExist(name string, instance interface{}) bool {
  59. return getGroup(name).SetIfNotExist(name, instance)
  60. }
  61. // Clear deletes all instances stored.
  62. func Clear() {
  63. for i := 0; i < groupNumber; i++ {
  64. groups[i].Clear()
  65. }
  66. }