syncdb.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package syncdb
  2. import (
  3. "fmt"
  4. "sync"
  5. "time"
  6. uuid "github.com/satori/go.uuid"
  7. )
  8. type SyncDB struct {
  9. db *sync.Map //HERE ALSO CHANGED, USE POINTER INSTEAD OF A COPY OF THE ORIGINAL SYNCNAMP
  10. }
  11. type dbStructure struct {
  12. timestamp time.Time
  13. value string
  14. }
  15. func NewSyncDB() *SyncDB {
  16. //Create a new SyncMap for this SyncDB Object
  17. newDB := sync.Map{}
  18. //Put the newly craeted syncmap into the db object
  19. newSyncDB := SyncDB{db: &newDB} //!!! USE POINTER HERE INSTEAD OF THE SYNC MAP ITSELF
  20. //Return the pointer of the new SyncDB object
  21. newSyncDB.AutoClening()
  22. return &newSyncDB
  23. }
  24. func (p SyncDB) AutoClening() {
  25. //create the routine for auto clean trash
  26. go func() {
  27. for {
  28. <-time.After(5 * 60 * time.Second) //no rush, clean every five minute
  29. p.db.Range(func(key, value interface{}) bool {
  30. if time.Now().Sub(value.(dbStructure).timestamp).Minutes() >= 30 {
  31. p.db.Delete(key)
  32. }
  33. return true
  34. })
  35. }
  36. }()
  37. }
  38. func (p SyncDB) Store(value string) string {
  39. uid := uuid.NewV4().String()
  40. NewField := dbStructure{
  41. timestamp: time.Now(),
  42. value: value,
  43. }
  44. p.db.Store(uid, NewField)
  45. return uid
  46. }
  47. func (p SyncDB) Read(uuid string) string {
  48. value, ok := p.db.Load(uuid)
  49. if !ok {
  50. return ""
  51. } else {
  52. return value.(dbStructure).value
  53. }
  54. }
  55. func (p SyncDB) Delete(uuid string) {
  56. p.db.Delete(uuid)
  57. }
  58. func (p SyncDB) ToString() {
  59. p.db.Range(func(key, value interface{}) bool {
  60. fmt.Print(key)
  61. fmt.Print(" : ")
  62. fmt.Println(value.(dbStructure).value)
  63. fmt.Print(" @ ")
  64. //fmt.Print(value.(dbStructure).timestamp)
  65. fmt.Print(time.Now().Sub(value.(dbStructure).timestamp).Seconds())
  66. fmt.Print("\n")
  67. return true
  68. })
  69. }