跳至主要內容

容器化微服务 Demo 项目开发笔记

Steven小于 1 分钟示例项目微服务

搭建 “课程管理系统” Demo,了解微服务架构玩法。

代码: https://github.com/LawssssCat/blog/tree/master/code/demo-microk8s/

编译 thrift 脚本

#!/bin/bash

SCRIPT_PATH=$(cd $(dirname $0); pwd)
PROJECT_PATH=$(cd $SCRIPT_PATH/../; pwd)

function copy_file() {
  local src="$1"
  local dst="$2"
  mkdir -pv ${dst%/*}
  cp -avf $src $dst
}

# message
thrift --gen py   -out ${PROJECT_PATH}/message-thrift-python-service/thrift_api/ ${PROJECT_PATH}/script/thrift/message.thrift
thrift --gen java -out ${PROJECT_PATH}/message-thrift-java-api/src/main/java/    ${PROJECT_PATH}/script/thrift/message.thrift

# user
thrift --gen java -out ${PROJECT_PATH}/user-thrift-java-api/src/main/java/ ${PROJECT_PATH}/script/thrift/user.thrift

信息服务(Python)

接口定义语言
namespace java org.example.thrift.message
namespace py message.api

service MessageService {
    bool sendMobileMessage(1:string mobile, 2:string message);
    bool sendEmailMessage(1:string email, 2:string message);
}

用户服务

接口实现

接口定义语言
namespace java org.example.thrift.user

struct UserInfo {
    1:i32 id,
    2:string username,
    3:string password,
    4:string readName,
    5:string mobile,
    6:string email,
}

service UserService {
    UserInfo getUserById(1:i32 id);
    UserInfo getUserByUsername(1:string username);
    void registerUser(1:UserInfo userInfo);
}

服务器

package org.example.thrift.user.thrift;

import lombok.extern.slf4j.Slf4j;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportException;
import org.apache.thrift.transport.TTransportFactory;
import org.example.thrift.user.UserService;
import org.example.thrift.user.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class ThriftServer {
    @Value("${thrift.server.port}")
    private int thriftServerPort;
    @Autowired
    private UserServiceImpl userServiceImpl;
    public void startThriftServer() {
        UserService.Processor<UserServiceImpl> userServiceProcessor = new UserService.Processor<>(userServiceImpl);
        try (TServerSocket socket = new TServerSocket(thriftServerPort)){
            TServer.Args serverArgs = new TServer.Args(socket);
            serverArgs.processor(userServiceProcessor);
            serverArgs.protocolFactory(new TBinaryProtocol.Factory());
            serverArgs.transportFactory(new TTransportFactory());
            // server
            TSimpleServer server = new TSimpleServer(serverArgs);
            log.info("TServer - Start serving...");
            server.serve();
        } catch (TTransportException e) {
            throw new RuntimeException(e);
        }
    }
}