redis_test.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package redis
  2. import (
  3. "fmt"
  4. "github.com/gomodule/redigo/redis"
  5. "github.com/spf13/viper"
  6. "math/rand"
  7. "strconv"
  8. "testing"
  9. )
  10. func TestRedisRepository(t *testing.T) {
  11. r := NewTestRepository()
  12. for i := 0; i < 10; i++ {
  13. err := r.Save2("test", []byte(strconv.Itoa(rand.Intn(100))), 0)
  14. if nil != err {
  15. println("Redis error:", err)
  16. }
  17. }
  18. }
  19. // Redis操作类示例
  20. type TestRepository struct {
  21. hub *Hub
  22. }
  23. func NewTestRepository() *TestRepository {
  24. viper.SetDefault("redis.host", "127.0.0.1:6379")
  25. hub := NewHub()
  26. return &TestRepository{hub: hub}
  27. }
  28. func (r *TestRepository) Save2(key string, value []byte, expire int) error {
  29. var err error
  30. var reply string
  31. if expire > 0 {
  32. reply, err = redis.String(r.hub.Do("SET", key, value, expire))
  33. } else {
  34. reply, err = redis.String(r.hub.Do("SET", key, value))
  35. }
  36. if nil != err {
  37. return err
  38. } else if reply != "" {
  39. println(reply)
  40. }
  41. return nil
  42. }
  43. func (r *TestRepository) Save(key string, value []byte) error {
  44. fmt.Printf("input: %s\n", string(value))
  45. var err error
  46. var i interface{}
  47. i, err = r.hub.Do("SET", key, value)
  48. if nil != err {
  49. fmt.Printf("%T\n", err)
  50. return err
  51. }
  52. fmt.Printf("%T\n", i)
  53. println(fmt.Sprintf("%s", i))
  54. return nil
  55. }
  56. func (r *TestRepository) Test(key string, value []byte) error {
  57. i, err := r.hub.Do("HSET", key, []byte("code"), value)
  58. if nil != err {
  59. fmt.Printf("%T\n", err)
  60. return err
  61. }
  62. fmt.Printf("%T\n", i)
  63. println(fmt.Sprintf("%d", i))
  64. return nil
  65. }