数据库是项目的核心,数据库的链接数据是data层的操作,选择了比较简单好用的gorm作为数据库的工具;之前是PHP开发,各种框架都是orm的操作;gorm还是很相似的,使用起来比较顺手
go-kratos官网的实例是ent,功能是很强大,操作稍微复杂点
gorm的官方文档 https://gorm.io/zh_CN/docs/index.html
使用
go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql
照葫芦画瓢先画起来再说
data.go 把数据库的链接放到NewData方法里面
package data
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
"xgs_kratos/gen/config/users"
"github.com/go-kratos/kratos/v2/log"
"github.com/google/wire"
)
// ProviderSet is data providers.
var ProviderSet = wire.NewSet(NewData, NewUserRepo, CreateRegister)
// Data .
type Data struct {
// TODO wrapped database client
db *gorm.DB
log *log.Helper
}
// NewData .
func NewData(c *conf.Data, logger log.Logger) (*Data, func(), error) {
cleanup := func() {
log.NewHelper(logger).Info("closing the data resources")
}
db, err := gorm.Open(mysql.Open(c.Database.Source), &gorm.Config{})
if err != nil {
log.Fatalf("failed to connect database: %v", err)
panic(err)
}
return &Data{
db: db,
log: log.NewHelper(logger),
}, cleanup, nil
}
user.proto加2个http的方法 ListUser 和 CreateUser
syntax = "proto3";
package gen.users;
import "google/api/annotations.proto";
option go_package = "xgs_kratos/gen/users;users";
option java_multiple_files = true;
option java_package = "api.users";
service User {
rpc CreateUser (CreateUserRequest) returns (CreateUserReply){
option (google.api.http) = {
post: "/CreateUser",
body: "*",
};
};
rpc UpdateUser (UpdateUserRequest) returns (UpdateUserReply);
rpc DeleteUser (DeleteUserRequest) returns (DeleteUserReply);
rpc GetUser (GetUserRequest) returns (GetUserReply);
rpc ListUser (ListUserRequest) returns (ListUserReply){
option (google.api.http) = {
get: "/ListUser",
};
};
}
message CreateUserRequest {
string name = 1;
string email = 2;
int32 age = 3;
}
message CreateUserReply {
int64 id = 1;
}
message UpdateUserRequest {}
message UpdateUserReply {}
message DeleteUserRequest {}
message DeleteUserReply {}
message GetUserRequest {}
message GetUserReply {}
message ListUserRequest {}
message UserData {
int64 id = 1;
string name = 2;
string email = 3;
int32 age = 4;
}
message ListUserReply {
repeated UserData users = 1;
}
需要再biz业务层和data数据层 实现
service/user.go
package service
import (
"context"
"xgs_kratos/app/users/internal/biz"
pb "xgs_kratos/gen/users"
)
type UserService struct {
pb.UnimplementedUserServer
uc *biz.UserUsecase
}
func NewUserService(uc *biz.UserUsecase) *UserService {
return &UserService{
uc: uc,
}
}
func (s *UserService) CreateUser(ctx context.Context, req *pb.CreateUserRequest) (*pb.CreateUserReply, error) {
user, err := s.uc.CreateUser(ctx, req)
if err != nil {
return nil, err
}
return user, nil
}
// func (s *UserService) UpdateUser(ctx context.Context, req *pb.UpdateUserRequest) (*pb.UpdateUserReply, error) {
// return &pb.UpdateUserReply{}, nil
// }
//
// func (s *UserService) DeleteUser(ctx context.Context, req *pb.DeleteUserRequest) (*pb.DeleteUserReply, error) {
// return &pb.DeleteUserReply{}, nil
// }
//
// func (s *UserService) GetUser(ctx context.Context, req *pb.GetUserRequest) (*pb.GetUserReply, error) {
// return &pb.GetUserReply{}, nil
// }
func (s *UserService) ListUser(ctx context.Context, req *pb.ListUserRequest) (*pb.ListUserReply, error) {
user, err := s.uc.ListUser(ctx, req)
if err != nil {
return nil, err
}
return &pb.ListUserReply{
Users: user,
}, nil
}
biz/user.go
package biz
import (
"context"
"github.com/go-kratos/kratos/v2/log"
"xgs_kratos/gen/users"
)
type User struct {
}
// UserRepo 定义数据仓库接口
type UserRepo interface {
CreateUser(ctx context.Context, req *users.CreateUserRequest) (*users.CreateUserReply, error)
ListUser(ctx context.Context, req *users.ListUserRequest) ([]*users.UserData, error)
}
// UserUsecase 定义业务逻辑
type UserUsecase struct {
repo UserRepo
log *log.Helper
}
// NewUsecase 创建Usecase
func NewUserUsecase(repo UserRepo, logger log.Logger) *UserUsecase {
return &UserUsecase{repo: repo, log: log.NewHelper(logger)}
}
// CreateUser 创建用户
func (uc *UserUsecase) CreateUser(ctx context.Context, req *users.CreateUserRequest) (*users.CreateUserReply, error) {
return uc.repo.CreateUser(ctx, req)
}
// ListUser 获取用户列表
func (uc *UserUsecase) ListUser(ctx context.Context, req *users.ListUserRequest) ([]*users.UserData, error) {
return uc.repo.ListUser(ctx, req)
}
我把数据表的模型放到了data/dal目录下了 app/users/internal/data/dal/user.go
package dal
type UserMo struct {
Id int64
Age int32
Name string
Email string
}
func (u *UserMo) TableName() string {
return "users"
}
data/user.go
package data
import (
"context"
"github.com/go-kratos/kratos/v2/log"
"xgs_kratos/app/users/internal/biz"
"xgs_kratos/app/users/internal/data/dal"
"xgs_kratos/gen/users"
)
//data 层处理数据的存储和读取
type userRepo struct {
data *Data
log *log.Helper
}
// NewUserRepo .
func NewUserRepo(data *Data, logger log.Logger) biz.UserRepo {
return &userRepo{
data: data,
log: log.NewHelper(logger),
}
}
// CreateUser 创建用户
func (r *userRepo) CreateUser(ctx context.Context, req *users.CreateUserRequest) (*users.CreateUserReply, error) {
user := dal.UserMo{
Age: req.Age,
Name: req.Name,
Email: req.Email,
}
result := r.data.db.Create(&user)
if result.Error != nil {
return nil, result.Error
}
return &users.CreateUserReply{
Id: user.Id,
}, nil
}
func (r *userRepo) ListUser(ctx context.Context, req *users.ListUserRequest) ([]*users.UserData, error) {
var results []dal.UserMo
res := r.data.db.Find(&results)
if res.Error != nil {
return nil, res.Error
}
var userDatas []*users.UserData
for _, result := range results {
userDatas = append(userDatas, &users.UserData{
Id: result.Id,
Name: result.Name,
Age: result.Age,
Email: result.Email,
})
}
return userDatas, nil
}
根目录下执行 buf generate
buf generate
kratos run
postman请求新增
获取列表
项目的代码 码云 https://gitee.com/gebilaoxie/xgs_kratos.git