Read the directory
- What is a service
- Building a service provider
- 1. Create table
- 2. Build the service provider
- 3. Install json RPC dependencies
- 4. Install the RPC Server component
- 5. Modify the server configuration
- 6. Configure the database
- 7. Write basic code
- 7-1. Write model code
- 7-2. Write service code
- Postman test
In the last article, we learned how to use HyperF to split projects vertically, which is the basis for our entire microservices module.
Hyperf supports JSON-RPC and gRPC. We introduced jSON-RPC and jSON-RPC request and response cases in distributed Services Architecture. Later we will focus on JSON-RPC as an example to solve various problems in microservices.
First, let’s define what a service is.
A service has two roles. One is a ServiceProvider that provides services for other services, and the other is a ServiceConsumer that depends on other services. A service may be a ServiceProvider. It is also a ServiceConsumer. In Hyperf, it can be directly understood as an Interface class. Generally, this Interface class will appear under both the provider and the consumer. — from the official website.
Simply put, our project module will be divided into service provider module and service consumer module. A service provider module is a module that provides various services and needs to interact with a database. Service consumer modules refer to modules that consume services. It requires remote access to the service provider.
The source code for this lesson has been uploaded to github, github.com/bailangzhan…
Let’s follow the steps to see how to build the service provider.
1. Create table
CREATE DATABASE hyperf; USE hyperf; CREATE TABLE 'user' (' id 'int(11) NOT NULL AUTO_INCREMENT,' name 'varchar(30) NOT NULL DEFAULT' COMMENT '名', 'gender' tinyint(1) NOT NULL DEFAULT '0' COMMENT 'gender 1 male 2 female 0 unknown ', 'created_AT' int(11) NOT NULL DEFAULT '0' COMMENT 'updated_at' int(11) NOT NULL DEFAULT '0' COMMENT 'updated_at ', PRIMARY KEY (' id ')) ENGINE=InnoDB DEFAULT CHARSET= utf8MB4 COMMENT=' InnoDB ';Copy the code
\
2. Build the service provider
composer create-project hyperf/hyperf-skeleton shop_provider_user
Copy the code
During the installation, we will be asked to select the default components. Except for the time zone and database, all other components will be selected “N”, as shown below
What time zone do you want to setup ? [n] Default time zone for php.ini Make your selection or type a time zone name, like Asia/Shanghai (n): Asia/Shanghai Do you want to use Database (MySQL Client) ? [y] yes [n] None of the above Make your selection or type a composer package name and version (yes): Y -Adding Package Hyperf /database (~2.2.0) -Adding Package Hyperf/db-Connection (~2.2.0) Do you want to use Redis Client ? [y] yes [n] None of the above Make your selection or type a composer package name and version (yes): n Which RPC protocol do you want to use ? [1] JSON RPC with Service Governance [2] JSON RPC [3] gRPC [n] None of the above Make your selection or type a composer package name and version (n): n Which config center do you want to use ? [1] Apollo [2] Aliyun ACM [3] ETCD [4] Nacos [n] None of the above Make your selection or type a composer package name and version (n): n Do you want to use hyperf/constants component ? [y] yes [n] None of the above Make your selection (n): n Do you want to use hyperf/async-queue component ? (A simple redis queue component) [y] yes [n] None of the above Make your selection or type a composer package name and version (n): n Do you want to use hyperf/amqp component ? [y] yes [n] None of the above Make your selection or type a composer package name and version (n): n Do you want to use hyperf/model-cache component ? [y] yes [n] None of the above Make your selection or type a composer package name and version (n): n Do you want to use hyperf/elasticsearch component ? [y] yes [n] None of the above Make your selection or type a composer package name and version (n): n Do you want to use hyperf/tracer component ? (An open tracing protocol component, adapte with Zipkin etc.) [y] yes [n] None of the above Make your selection or type a composer package name and version (n): nCopy the code
We can add any components we need later.
\
3. Install json RPC dependencies
cd shop_provider_user
composer require hyperf/json-rpc
Copy the code
\
4. Install the RPC Server component
We are going to let the Shop_PROVIDer_user application provide services externally, so we need to install the RPC Server component
composer require hyperf/rpc-server
Copy the code
\
5. Modify the server configuration
Shop_provider_user provides jSONRPC service and does not need to provide HTTP service. Therefore, the HTTP service configuration is masked and the jSONrpc-HTTP service is added.
Hyperf supports the JSONRpc-HTTP protocol, JSONRPC protocol, and JSONRpc-TCP-Length-Check protocol. Jsonrpc-http is used as an example in the following sections.
The following configuration in config/autoload/server PHP file, note jsonrpc – HTTP service configuration of the port number is 9600
'the servers = > / / / / / /' name '= >' HTTP '/ /' type '= > Server: : SERVER_HTTP, / /' host '= >' 0.0.0.0 '/ /' port '= > 9501, // 'sock_type' => SWOOLE_SOCK_TCP, // 'callbacks' => [ // Event::ON_REQUEST => [Hyperf\HttpServer\Server::class, 'onRequest'], / /, / /], [' name '= >' jsonrpc - HTTP ', 'type' = > Server: : SERVER_HTTP, 'host' = > '0.0.0.0', 'port' => 9600, 'sock_type' => SWOOLE_SOCK_TCP, 'callbacks' => [ Event::ON_REQUEST => [\Hyperf\JsonRpc\HttpServer::class, 'onRequest'], ], ], ],Copy the code
\
6. Configure the database
Modify the. Env file, APP_NAME and database configuration
APP_NAME=shop_provider_user DB_DRIVER=mysql DB_HOST=192.168.33.20 DB_PORT=3306 DB_DATABASE= Hyperf DB_USERNAME= WWW DB_PASSWORD=123456 DB_CHARSET=utf8mb4 DB_COLLATION=utf8mb4_unicode_ci DB_PREFIX=Copy the code
\
7. Write basic code
\
7-1. Write model code
Generate model and modify it as follows:
PHP bin/hyperf.php gen:model User [app/ model/user.php] <? php declare (strict_types=1); namespace App\Model; use Hyperf\DbConnection\Model\Model; /** */ class User extends Model { /** * The table associated with the model. * * @var string */ protected $table = 'user'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['name', 'gender']; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = ['id' => 'integer', 'gender' => 'integer']; $dateFormat = 'U'; $dateFormat = 'U'; }Copy the code
\
7-2. Write service code
Create the JsonRpc directory under app and write the userService. PHP and UserServiceInterface.
UserServiceInterface Provides two interfaces, one for creating users and the other for obtaining user information.
【 UserServiceInterface 】 <? php namespace App\JsonRpc; interface UserServiceInterface { public function createUser(string $name, int $gender); public function getUserInfo(int $id); } 【UserService】 <? php namespace App\JsonRpc; use App\Model\User; use Hyperf\RpcServer\Annotation\RpcService; /** * @RpcService(name="UserService", protocol="jsonrpc-http", server="jsonrpc-http") */ class UserService implements UserServiceInterface { /** * @param string $name * @param string $gender * @return string */ public function createUser(string $name, Int $gender) {if (empty($name)) {throw new \RuntimeException("name cannot be empty "); } $result = User::query()->create([ 'name' => $name, 'gender' => $gender, ]); return $result ? "success" : "fail"; } /** * @param int $id * @return array */ public function getUserInfo(int $id) { $user = User::query()->find($id); if (empty($user)) { throw new \RuntimeException("user not found"); } return $user->toArray(); }}Copy the code
Notice that in the UserService class, we use the @rpcService Annotation. Use Hyperf\RpcServer\Annotation\RpcService;
Hyperf\RpcServer\Annotation\RpcService: Hyperf\RpcServer\Annotation\RpcService
- The name attribute defines the name of the service. Do not use the same name for different services. The name is unique, and Hyperf will generate the corresponding ID to register with the service center.
- The protocol attribute defines the protocol exposed by the service. Currently, only JSONRpc-HTTP, JSONRPC, and JSONRpc-TCP-Length-Check are supported, which correspond to the two protocols under HTTP and TCP respectively. The default value is jSONrpc-HTTP, where the value corresponds to the key of the protocol registered in Hyperf\Rpc\ProtocolManager. They are all JSON Rpc protocols in nature, and the differences lie in data formatting, data packaging, and data transfer.
- Server properties for the binding of the service class to hosting server, the default value is jsonrpc – HTTP, this attribute corresponding to the config/autoload/server under the servers within the PHP file that corresponds to the name;
- The publishTo attribute defines the service center to be published by the service. Currently, only Consul and nacos are supported or left blank
At this point we have built a basic service provider.
\
Postman test
Let’s test whether these two interfaces work properly. Run the PHP bin/hyperf.php start command to start the service and send requests using Postman.
Request address: http://127.0.0.1:9600 Request method: POST Request parameters {"jsonrpc": "2.0", "method": "/user/createUser", "params": {"name": "Zhangsan ", "gender": 3}," ID ": "61025bc35e07d", "context": []} header Content-type: {" jSONRPC ": "2.0", "ID ":" 61025BC35e07d ", "result": "success", "context": []}Copy the code
\
\
Look at the data sheet
\
\
The created_AT and update_AT fields are populated automatically.
Try using postman to access /user/getUserInfo.
Request address: http://127.0.0.1:9600 Request method: POST Request parameters {" jSONRPC ": "2.0", "method": "/user/getUserInfo", "params": {"id": 1}, "ID ":" 61025BC35e07D ", "context": []} Header Header Content-Type: application/json Response result {" jSONRPC ": "2.0", "ID ": "61025bc35e07d", "result": { "id": 1, "name": "zhangsan", "gender": 3, "created_at": "1630101991", "updated_at": "1630101991" }, "context": [] }Copy the code
At this point, our service provider is basically set up. For those of you who may have read about Consul in other articles, we’ll be covering more on Consul in the future, so stay tuned.
In the next section, we continue building service consumers.