go-micro.dev/v5@v5.12.0/internal/website/docs/store.md (about)

     1  ---
     2  layout: default
     3  ---
     4  
     5  # Store
     6  
     7  The store provides a pluggable interface for data storage in Go Micro.
     8  
     9  ## Features
    10  - Key-value storage
    11  - Multiple backend support
    12  
    13  ## Implementations
    14  Supported stores include:
    15  - Memory (default)
    16  - File (`go-micro.dev/v5/store/file`)
    17  - MySQL (`go-micro.dev/v5/store/mysql`)
    18  - Postgres (`go-micro.dev/v5/store/postgres`)
    19  - NATS JetStream KV (`go-micro.dev/v5/store/nats-js-kv`)
    20  
    21  Plugins are scoped under `go-micro.dev/v5/store/<plugin>`.
    22  
    23  Configure the store in code or via environment variables.
    24  
    25  ## Example Usage
    26  
    27  Here's how to use the store in your Go Micro service:
    28  
    29  ```go
    30  package main
    31  
    32  import (
    33      "go-micro.dev/v5"
    34      "go-micro.dev/v5/store"
    35      "log"
    36  )
    37  
    38  func main() {
    39      service := micro.NewService()
    40      service.Init()
    41  
    42      // Write a record
    43      if err := store.Write(&store.Record{Key: "foo", Value: []byte("bar")}); err != nil {
    44          log.Fatal(err)
    45      }
    46  
    47      // Read a record
    48      recs, err := store.Read("foo")
    49      if err != nil {
    50          log.Fatal(err)
    51      }
    52      log.Printf("Read value: %s", string(recs[0].Value))
    53  }
    54  ```
    55  
    56  ## Configure a specific store in code
    57  
    58  Postgres:
    59  ```go
    60  import (
    61      "go-micro.dev/v5"
    62      postgres "go-micro.dev/v5/store/postgres"
    63  )
    64  
    65  func main() {
    66      st := postgres.NewStore()
    67      svc := micro.NewService(micro.Store(st))
    68      svc.Init()
    69      svc.Run()
    70  }
    71  ```
    72  
    73  NATS JetStream KV:
    74  ```go
    75  import (
    76      "go-micro.dev/v5"
    77      natsjskv "go-micro.dev/v5/store/nats-js-kv"
    78  )
    79  
    80  func main() {
    81      st := natsjskv.NewStore()
    82      svc := micro.NewService(micro.Store(st))
    83      svc.Init()
    84      svc.Run()
    85  }
    86  ```
    87  
    88  ## Configure via environment
    89  
    90  ```bash
    91  MICRO_STORE=postgres MICRO_STORE_ADDRESS=postgres://user:pass@127.0.0.1:5432/db \
    92  MICRO_STORE_DATABASE=micro MICRO_STORE_TABLE=micro \
    93  go run main.go
    94  ```
    95  
    96  Common variables:
    97  - `MICRO_STORE`: selects the store implementation (`memory`, `file`, `mysql`, `postgres`, `nats-js-kv`).
    98  - `MICRO_STORE_ADDRESS`: connection/address string for the store (plugin-specific format).
    99  - `MICRO_STORE_DATABASE`: logical database or namespace (plugin-specific).
   100  - `MICRO_STORE_TABLE`: logical table/bucket (plugin-specific).