In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
In this issue, the editor will bring you what the simple micro-service of go-micro+php+consul is like. The article is rich in content and analyzes and describes it from a professional point of view. I hope you can get something after reading this article.
First we use go-micro to build a service. (you can refer to official examples or documents about the use of go-micro)
/ / create a new microservice micro new-- type "srv" user-srv
Define our services. Here we define two rpc services, Register and User
/ modify protosyntax = "proto3"; package go.micro.srv.user;service User {rpc Register (RegisterRequest) returns (UserInfo) {} rpc User (UserInfoRequest) returns (UserInfo) {} rpc Stream (StreamingRequest) returns (stream StreamingResponse) {} rpc PingPong (stream Ping) returns (stream Pong) {} message UserInfoRequest {int64 userId = 1;} message RegisterRequest {string username = 1; string email = 2; string password = 3 } message UserInfo {int64 id = 1; string username = 2; string email = 3;} message StreamingRequest {int64 count = 1;} message StreamingResponse {int64 count = 1;} message Ping {int64 stroke = 1;} message Pong {int64 stroke = 1;}
Then generate and execute the following command and we can find two more files in the proto file. This proto is generated for us and will be used later.
Protoc-- proto_path=$ {GOPATH} / src:. -- micro_out=. -- go_out=. Proto/user/user.proto
Write our business logic and modify the handle/user.go file
Type User struct {} / / Call is a single request handler called via client.Call or the generated client codefunc (e * User) Register (ctx context.Context, req * user.RegisterRequest, rsp * user.UserInfo) error {log.Log ("Received User.Register request") rsp.Id = 1 rsp.Email = req.Email rsp.Username = req.Username return nil} func (e * User) User (ctx context.Context, req * user.UserInfoRequest Rsp * user.UserInfo) error {log.Log ("Received User.Register request") rsp.Id = 1 rsp.Email = "741001560@qq.com" rsp.Username = "chensi" return nil} / / Stream is a server side stream handler called via client.Stream or the generated client codefunc (e * User) Stream (ctx context.Context, req * user.StreamingRequest, stream user.User_StreamStream) error {log.Logf ("Received User.Stream request with count:% d" Req.Count) for I: = 0 I
< int(req.Count); i++ { log.Logf("Responding: %d", i) if err := stream.Send(&user.StreamingResponse{ Count: int64(i), }); err != nil { return err } } return nil}// PingPong is a bidirectional stream handler called via client.Stream or the generated client codefunc (e *User) PingPong(ctx context.Context, stream user.User_PingPongStream) error { for { req, err := stream.Recv() if err != nil { return err } log.Logf("Got ping %v", req.Stroke) if err := stream.Send(&user.Pong{Stroke: req.Stroke}); err != nil { return err } }} 最后修改我们的main.go文件,服务发现使用时consul。 func main() { //initCfg() // New Service micReg := consul.NewRegistry() service := micro.NewService( micro.Server(s.NewServer()), micro.Name("go.micro.srv.user"), micro.Version("latest"), micro.Registry(micReg), ) // Initialise service service.Init() // Run service if err := service.Run(); err != nil { log.Fatal(err) }} 我们使用consul做微服务发现,当然首先你需要安装consul wget https://releases.hashicorp.com/consul/1.2.0/consul_1.6.1_linux_amd64.zip unzip consul_1.6.1_linux_amd64.zip mv consul /usr/local/bin/ 启动consul的时候由于在是本地虚拟机上面,所以我们可以简单处理 consul agent -dev -client 0.0.0.0 -ui 这时候可以启动consul的ui了,我本地vagrant的虚拟机192.168.10.100,那么我们打开的是http://192.168.10.100:8500/ui/dc1/services 启动user-srv的服务发现consul里面出现 go.micro.srv.user 的服务注册信息了 下面来写hyperf的代码了。按照官方文档安装框架,安装的时候rpc需要选择grpc,需要注意的是你的系统上面需要安装php7.2以上的版本,swoole版本也需要4.3的版本以上,我用的是最新homestead,所以相对而言安装这些依赖比较简单,所以在此强烈推荐。 第一次启动时候官方会要求修改一些php.ini的参数,大家安装要求走就是了。 这部分的流程自己参照官方文档,至于一些扩展的安装可以谷歌或者百度。 安装好框架之后再根目录下面新建一个grpc和proto的目录,把go-micro里面user.proto文件复制到hyperf项目的proto的目录之下。然后在目录下执行命令 protoc --php_out=plugins=grpc:../grpc user.proto 执行成功之后会发现在grpc目录下多出两个文件夹。 接下来我们开始编写client的代码,在hyperf项目的app目录下新建一个Grpc的目录并且新建一个UserClient.php的文件 namespace App\Grpc;use Go\Micro\Srv\User\RegisterRequest;use Go\Micro\Srv\User\UserInfo;use Hyperf\GrpcClient\BaseClient;class UserClient extends BaseClient{ public function Register(RegisterRequest $argument) { return $this->SimpleRequest ('/ user.User/Register', $argument, [UserInfo::class, 'decode']);}
With regard to this piece of code, in fact, the official documentation is very detailed, you can refer to the official documentation.
Create a new route
Router::addRoute (['GET',' POST', 'HEAD'],' / grpc', 'App\ Controller\ IndexController@grpc')
Write a controller
Public function grpc () {$client = new\ App\ Grpc\ UserClient ('127.0.0.1 App 9527mm, [' credentials' = > null,]); $request = new RegisterRequest (); $request- > setEmail ("741001560@qq.com"); $request- > setUsername ("chensi"); $request- > setPassword ("123456") / * * @ var\ Grpc\ HiReply $reply * / list ($reply, $status) = $client- > Register ($request); $message = $reply- > getId (); return ['id' = > $message];}
At this point, you also need to load the grpc directory under the root directory. Modify the composer.json file
Two new lines "autoload" are added under ```/ / psr-4: {"psr-4": {"App\\": "app/", "GPBMetadata\\": "grpc/GPBMetadata", "Go\\": "grpc/Go"}, "files": []}
Then execute the composer dump-autoload command. Then start the hyperf project, open a browser and enter http://192.168.10.100:9501/grpc, and then we can see the results.
At this point, we will find a problem, that is, consul is not used at all on the client side, and we still need to specify our port number in the code. Then take a look at the official documentation that actually supports consul, so modify the code.
Create a new Register directory under app to create a file ConsulServices.php, and then start writing the code for service discovery. After installing the consul package, you need to look at the source code yourself because the official consul package has no documentation. Officials have done simple encapsulation on the api provided by consul, such as KV, Health, etc., and you need to pass through a client when instantiating the message. A simple example is provided below.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.