0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Goでredis

アドベントカレンダー8日目です。
redisを扱います。

環境を作る

version: '3'
services:
  golang:
    build: .
    tty: true
    volumes:
      - ./:/app/
    ports:
      - "1323:1323"
  mysql:
    image: mariadb
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: golang
      MYSQL_USER: golang
      MYSQL_PASSWORD: golang
    restart: always
    ports:
      - "3310:3306"
    volumes:
      - ./mysql:/var/lib/mysql
  redis:
    image: "redis:latest"
    ports:
      - "6379:6379"
    volumes:
      - "./data/redis:/data"

コンテナを起動

docker-compose up -d

接続確認

$ docker-compose exec redis sh
# redis-cli
127.0.0.1:6379>

よさそうです。

goからredisを操作する

ライブラリはgo-redisを使います。
https://github.com/redis/go-redis

プログラム本文

docker-compose exec golang go get github.com/go-redis/redis
mkdir app/day8/ && touch app/day8/main.go
package main

import (
	"fmt"

	"github.com/go-redis/redis"
)

type RedisAdapter struct {
	client *redis.Client
}

func NewRedisAdapter() *RedisAdapter {
	client := redis.NewClient(&redis.Options{
		Addr:     "redis:6379", // コンテナの名前:ポート番号
		Password: "",
		DB:       0,
	})

	_, err := client.Ping().Result()
	if err != nil {
		panic(err)
	}

	return &RedisAdapter{
		client: client,
	}
}

func (r *RedisAdapter) Set(key string, value string) error {
	err := r.client.Set(key, value, 0).Err()
	if err != nil {
		return err
	}
	return nil
}

func (r *RedisAdapter) Get(key string) (string, error) {
	val, err := r.client.Get(key).Result()
	if err != nil {
		return "", err
	}
	return val, nil
}

func main() {
	redisAdapter := NewRedisAdapter()

	err := redisAdapter.Set("key", "valueです")
	if err != nil {
		fmt.Println("Error setting value:", err)
	}

	value, err := redisAdapter.Get("key")
	if err != nil {
		fmt.Println("Error getting value:", err)
	} else {
		fmt.Println("Value:", value)
	}
}

プログラムを実行してみる

root@8f93343dfdb9:/app# go run app/day8/main.go
Value: valueです

redis-cliからも確認

$ docker-compose exec redis sh
# redis-cli
127.0.0.1:6379> keys *
1) "key"
127.0.0.1:6379> get key
"value\xe3\x81\xa7\xe3\x81\x99"
127.0.0.1:6379>

よさそうです。

最後に

これまで、httpサーバー、json、mysql等を扱ってきました。
明日は、これらを組み合わせることでwebアプリをガッツリ作ってみます。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?