前言
在实际的业务场景中,很多业务需要用到数据库。从本文开始,我们将以server+mysql的方式来探索一下在K8S中如何部署业务+数据库的使用场景。首先我们研究一下server和mysql两个容器部署在同一个POD中的情况。
一、访问mysql的server程序
修改server.cpp代码,增加mysql访问获取数据返回给客户端,由于server和mysql部署在同一个POD中,所以server可以通过localhost来访问mysql,参考代码如下:
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <sys/wait.h>
#include <poll.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <string>
#include <mysql/mysql.h>
#define ERR_EXIT(m) \
do \
{
\
perror(m); \
exit(EXIT_FAILURE); \
} while(0)
typedef std::vector<struct pollfd> PollFdList;
int main(void)
{
signal(SIGPIPE, SIG_IGN);
signal(SIGCHLD, SIG_IGN);
int listenfd;
if ((listenfd = socket(PF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, IPPROTO_TCP)) < 0)
ERR_EXIT("socket");
struct sockaddr_in servaddr