0
0

GoとRedisで作る簡単従業員管理アプリ

Posted at

GoとRedisの勉強のために作りました

こんにちは!今回は、Go言語とRedisを使って、シンプルだけど便利な従業員管理アプリを作っていきます。プログラミング初心者の方も、ベテランの方も、一緒に楽しく学んでいきましょう!

1. 環境設定

まずは開発環境を整えましょう。GoとRedisをインストールして、必要なパッケージも用意します。

go mod init employee-app
go get github.com/go-redis/redis/v8

これで準備オッケーです!さぁ、コーディングを始めましょう。

2. Redisクライアントの設定

次に、Redisに接続するためのクライアントを設定します。

package main

import (
    "context"
    "github.com/go-redis/redis/v8"
)

var ctx = context.Background()

func newRedisClient() *redis.Client {
    return redis.NewClient(&redis.Options{
        Addr: "localhost:6379",
    })
}

これで、Redisとの通信準備が整いました。簡単でしょう?

3. 従業員データ構造の定義

従業員の情報をどう保存するか考えましょう。構造体を使うと便利ですよ。

type Employee struct {
    ID        string
    Name      string
    Position  string
    Salary    int
}

シンプルだけど、必要な情報は押さえていますね。

4. 従業員の追加機能

さて、従業員を追加する関数を作りましょう。

func addEmployee(client *redis.Client, emp Employee) error {
    key := "employee:" + emp.ID
    return client.HSet(ctx, key,
        "name", emp.Name,
        "position", emp.Position,
        "salary", emp.Salary,
    ).Err()
}

この関数を使えば、簡単に従業員をRedisに追加できますよ。

5. 従業員情報の取得

追加した従業員の情報を取得する関数も必要ですね。

func getEmployee(client *redis.Client, id string) (Employee, error) {
    key := "employee:" + id
    val, err := client.HGetAll(ctx, key).Result()
    if err != nil {
        return Employee{}, err
    }

    salary, _ := strconv.Atoi(val["salary"])
    return Employee{
        ID:       id,
        Name:     val["name"],
        Position: val["position"],
        Salary:   salary,
    }, nil
}

これで、IDを指定するだけで従業員の情報が取得できます。便利ですね!

6. 従業員リストの表示

全従業員のリストを表示する機能も作りましょう。

func listEmployees(client *redis.Client) ([]Employee, error) {
    keys, err := client.Keys(ctx, "employee:*").Result()
    if err != nil {
        return nil, err
    }

    employees := []Employee{}
    for _, key := range keys {
        id := strings.TrimPrefix(key, "employee:")
        emp, err := getEmployee(client, id)
        if err != nil {
            continue
        }
        employees = append(employees, emp)
    }
    return employees, nil
}

これで全従業員の情報が一覧で見られますよ。

7. メイン関数とアプリの実行

最後に、これまでの機能を組み合わせてアプリを実行しましょう。

func main() {
    client := newRedisClient()
    defer client.Close()

    // 従業員を追加
    addEmployee(client, Employee{ID: "001", Name: "山田太郎", Position: "エンジニア", Salary: 350000})
    addEmployee(client, Employee{ID: "002", Name: "佐藤花子", Position: "デザイナー", Salary: 320000})

    // 従業員情報を取得
    emp, _ := getEmployee(client, "001")
    fmt.Printf("従業員ID 001: %+v\n", emp)

    // 全従業員リストを表示
    employees, _ := listEmployees(client)
    fmt.Println("全従業員リスト:")
    for _, e := range employees {
        fmt.Printf("%+v\n", e)
    }
}

これで完成です!実行すると、従業員の追加、情報取得、リスト表示ができるシンプルな従業員管理アプリの完成です。

いかがでしたか?GoとRedisを使えば、こんなに簡単に従業員管理アプリが作れるんです。ぜひ、このコードを基に自分なりにアレンジしてみてくださいね。楽しいコーディングライフを!

0
0
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
0