single_template.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package main
  2. var _singleTemplate = `
  3. // NAME {{or .Comment "get data from cache if miss will call source method, then add to cache."}}
  4. func (d *Dao) NAME(c context.Context, id KEY{{.ExtraArgsType}}) (res VALUE, err error) {
  5. addCache := true
  6. res, err = CACHEFUNC(c, id {{.ExtraCacheArgs}})
  7. if err != nil {
  8. addCache = false
  9. err = nil
  10. }
  11. {{if .EnableNullCache}}
  12. defer func() {
  13. {{if .SimpleValue}} if res == {{.NullCache}} { {{else}} if {{.CheckNullCode}} { {{end}}
  14. res = {{.ZeroValue}}
  15. }
  16. }()
  17. {{end}}
  18. {{if .GoValue}}
  19. if len(res) != 0 {
  20. {{else}}
  21. if res != {{.ZeroValue}} {
  22. {{end}}
  23. prom.CacheHit.Incr("NAME")
  24. return
  25. }
  26. {{if .EnablePaging}}
  27. var miss VALUE
  28. {{end}}
  29. {{if .EnableSingleFlight}}
  30. var rr interface{}
  31. sf := d.cacheSFNAME(id {{.ExtraArgs}})
  32. rr, err, _ = cacheSingleFlights[SFNUM].Do(sf, func() (r interface{}, e error) {
  33. prom.CacheMiss.Incr("NAME")
  34. {{if .EnablePaging}}
  35. var rrs [2]interface{}
  36. rrs[0], rrs[1], e = RAWFUNC(c, id {{.ExtraRawArgs}})
  37. r = rrs
  38. {{else}}
  39. r, e = RAWFUNC(c, id {{.ExtraRawArgs}})
  40. {{end}}
  41. return
  42. })
  43. {{if .EnablePaging}}
  44. res = rr.([2]interface{})[0].(VALUE)
  45. miss = rr.([2]interface{})[1].(VALUE)
  46. {{else}}
  47. res = rr.(VALUE)
  48. {{end}}
  49. {{else}}
  50. prom.CacheMiss.Incr("NAME")
  51. {{if .EnablePaging}}
  52. res, miss, err = RAWFUNC(c, id {{.ExtraRawArgs}})
  53. {{else}}
  54. res, err = RAWFUNC(c, id {{.ExtraRawArgs}})
  55. {{end}}
  56. {{end}}
  57. if err != nil {
  58. return
  59. }
  60. {{if .EnablePaging}}
  61. {{else}}
  62. miss := res
  63. {{end}}
  64. {{if .EnableNullCache}}
  65. {{if .GoValue}}
  66. if len(miss) == 0 {
  67. {{else}}
  68. if miss == {{.ZeroValue}} {
  69. {{end}}
  70. miss = {{.NullCache}}
  71. }
  72. {{end}}
  73. if !addCache {
  74. return
  75. }
  76. {{if .Sync}}
  77. ADDCACHEFUNC(c, id, miss {{.ExtraAddCacheArgs}})
  78. {{else}}
  79. d.cache.Do(c, func(c context.Context) {
  80. ADDCACHEFUNC(c, id, miss {{.ExtraAddCacheArgs}})
  81. })
  82. {{end}}
  83. return
  84. }
  85. `