数据库应用之--Redis+mysql实现大量数据的读写,以及高并发
一、开发背景
在项目开发过程中中遇到了以下三个需求:
1. 多个用户同时上传数据;
2. 数据库需要支持同时读写;
3. 1分钟内存储上万条数据;
根据对Mysql的测试情况,遇到以下问题:
1. 最先遇到压力的是服务器,在写入2500-3000条数据时,服务器崩溃了;
2. 当数据库写入时,耗时太长,10000条数据,大概需要505.887s,相当于8分钟,如下:
a. 表结构:

b. 数据库Procedure:
DROP PROCEDURE IF EXISTS my_insert;
CREATE PROCEDURE my_insert()
BEGIN
DECLARE n int DEFAULT 1;
loopname:LOOP
INSERT INTO car_pathinfo_driver_cpy(id, linkphone,cartype,carcolor,carnumber,drivername,pubtimes)VALUES(n+500,'','雪弗兰','白','豫A190XS','siker','');
SET n=n+1;
IF n=10000 THEN
LEAVE loopname;
END IF;
END LOOP loopname;
END;
CALL my_insert();
c. 运行结果如下:

3. 不断的数据库写入导致数据库压力过大;
出现以上问题,是由于mysql是基于磁盘的IO,基于服务响应性能考虑,就需要给数据做缓存,所以决定使用Mysql+redis缓存的解决方案,将业务热数据写入Redis缓存,使得高频业务数据可以直接从内存读取,提高系统整体响应速度。
二、使用Redis+Mysql需要考虑的问题
使用redis缓存+mysql数据库存储能解决:
1. 数据读写的速度
2. 服务器的压力问题
同时,就需要考虑同步问题了,Redis和Mysql的同步问题
三、Redis+mysql同步解决方案
1.写Redis->redis写mysql,读Mysql。
以下是一个Redis+mysql同步的示例,该示例测试了写入100000条数据的效率,先向Redis写入100000条数据,再将数据读出,写入Mysql。
批量写入缓解了服务器的压力。
stdafx.h
// stdafx.h : 标准系统包含文件的包含文件,
// 或是经常使用但不常更改的
// 特定于项目的包含文件
// #pragma once #include "targetver.h" #include <stdio.h>
#include <tchar.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <assert.h>
#include <vector>
#include "hiredis.h"
#include <Windows.h>
#include "mysql.h" #ifdef _DEBUG
#pragma comment(lib, "hiredis_d.lib")
#pragma comment(lib, "Win32_Interop_d.lib")
#else
#pragma comment(lib, "hiredis.lib")
#pragma comment(lib, "Win32_Interop.lib") #endif
#pragma comment(lib, "AdvAPI32.Lib")
#pragma comment(lib, "DbgHelp.Lib")
#pragma comment (lib, "Shlwapi.lib")
#pragma comment(lib,"libmysql.lib") using namespace std; typedef struct testData
{
int iHeight;
int iWidth;
char szValue[];
char szHValue[];
}stTestData, *pstTestData;
test.h
#include "stdafx.h"
#include "DBHandle.h" int main()
{ DBHandle *dbHandle = new DBHandle();
thread tWriteDataToRedis(&DBHandle::writeHsetToRedis, *dbHandle);
tWriteDataToRedis.join(); return ;
}
DBHandle.h
#pragma once
#include <mutex>
#include <thread> class DBHandle
{
public:
DBHandle();
~DBHandle(); bool connectRedis(string strIp, int iPort, string strPwd);
void freeRedis(); int getRedisDBSize(); bool writeHsetToRedis();
bool readDataFromRedis(); bool connectMysql();
void FreeMysqlConnect(); bool insertDataToMysql(string strData); redisContext* m_pRedisContext;
MYSQL m_mysql;
MYSQL_RES *res; //行的一个查询结果集 };
DBHandle.cpp
#include "stdafx.h"
#include "DBHandle.h" DBHandle::DBHandle()
{
m_pRedisContext = NULL;
} DBHandle::~DBHandle()
{
if (m_pRedisContext != NULL)
{
m_pRedisContext = NULL;
}
} bool DBHandle::connectRedis(string strIp, int iPort, string strPwd)
{
//redis默认监听端口为6387 可以再配置文件中修改
char szBuf[] = {};
strcpy_s(szBuf, sizeof(strIp), strIp.c_str());
m_pRedisContext = redisConnect(szBuf, iPort);
if (NULL == m_pRedisContext || m_pRedisContext->err)
{
return false;
} //输入Redis密码
strcpy_s(szBuf, sizeof(strPwd), strPwd.c_str());
redisReply *pRedisReply = (redisReply*)redisCommand(m_pRedisContext, "AUTH %s", szBuf);
if (NULL != pRedisReply)
{
freeReplyObject(pRedisReply);
}
if (NULL == pRedisReply->str)
{
return false;
}
return true; } void DBHandle::freeRedis()
{
redisFree(m_pRedisContext);
if (m_pRedisContext != NULL)
{
m_pRedisContext = NULL;
}
} int DBHandle::getRedisDBSize()
{
//查看list长度
int iListLen = ;
//redisReply *pRedisReply = (redisReply *)redisCommand(m_pRedisContext, "LLen datalist");
redisReply *pRedisReply = (redisReply *)redisCommand(m_pRedisContext, "DBSIZE");
if (NULL != pRedisReply)
{
if (NULL == pRedisReply->integer)
{
return false;
}
iListLen = pRedisReply->integer;
freeReplyObject(pRedisReply);
}
if (NULL == pRedisReply)
{
printf("%s \r\n", m_pRedisContext->errstr);
return false;
} return iListLen;
} bool DBHandle::writeHsetToRedis()
{
bool bFlag = connectRedis("127.0.0.1", , "");
if (false == bFlag)
{
return false;
} time_t st = time(NULL);//秒
stTestData data = {};
int i = ;
while (i<)
{ data.iHeight = i;
data.iWidth = ;
char szBuf[] = {};
sprintf_s(szBuf, "width%d", i);
strcpy_s(data.szValue, , szBuf);
sprintf_s(data.szHValue, "%s%d", "heighttest", i); //向Redis写入数据hset location (interger)1 "width"
sprintf_s(szBuf, "hset location%d value %s", i, data.szValue);
redisReply *pRedisReply = (redisReply *)redisCommand(m_pRedisContext, szBuf);
if (NULL != pRedisReply)
{
freeReplyObject(pRedisReply);
}
i++;
} printf("write finish");
readDataFromRedis(); time_t et = time(NULL);
int iUsed = st - et;
printf("used time is %d", iUsed);
freeRedis();
return true; } bool DBHandle::readDataFromRedis()
{
/*bool bFlag = connectRedis("127.0.0.1", 6379, "123456");
if (false == bFlag)
{
return false;
}*/ printf("read start"); int iSize = getListSize();
if (iSize <= )
{
return false;
}
bool bSuc = connectMysql();
if (bSuc == false)
{
return false;
} int iCount = iSize;//计数
while (iCount > )
{
//用get命令获取数据
redisReply *pRedisReply = (redisReply*)redisCommand(m_pRedisContext, "RPOP datalist");
if (NULL == pRedisReply)
{
return false;
}
if (NULL != pRedisReply->str)
{
string str = pRedisReply->str;
insertDataToMysql(str);
freeReplyObject(pRedisReply);
}
iCount--;
} printf("read finish"); return true; } bool DBHandle::connectMysql()
{
mysql_init(&m_mysql); // Connects to a MySQL server
const char host[] = "192.168.4.8";
const char user[] = "root";
const char passwd[] = "";
const char db[] = "topproductline";
unsigned int port = ;
const char *unix_socket = NULL;
unsigned long client_flag = ; /*A MYSQL* connection handler if the connection was successful,
NULL if the connection was unsuccessful. For a successful connection,
the return value is the same as the value of the first parameter.*/
if (mysql_real_connect(&m_mysql, host, user, passwd, db, port, unix_socket, client_flag)) {
printf("The connection was successful.\n");
return true;
}
else {
printf("Error connecting to database:%s\n", mysql_error(&m_mysql));
return false;
}
} void DBHandle::FreeMysqlConnect()
{
mysql_free_result(res);
mysql_close(&m_mysql);
} bool DBHandle::insertDataToMysql(string strData)
{
char szQuery[] = {};
sprintf_s(szQuery, "insert into a_test (type) values ('%s');", strData.c_str());
if (mysql_query(&m_mysql, szQuery)) {
printf("Query failed (%s)\n", mysql_error(&m_mysql));
return false;
}
else {
printf("Insert success\n");
return true;
}
}
测试结果:

2.写redis->写mysql,读Redis->未找到->读Mysql
数据库应用之--Redis+mysql实现大量数据的读写,以及高并发的更多相关文章
- redis和memcached有什么区别?redis的线程模型是什么?为什么单线程的redis比多线程的memcached效率要高得多(为什么redis是单线程的但是还可以支撑高并发)?
1.redis和memcached有什么区别? 这个事儿吧,你可以比较出N多个区别来,但是我还是采取redis作者给出的几个比较吧 1)Redis支持服务器端的数据操作:Redis相比Memcache ...
- 心知天气数据API 产品的高并发实践
心知天气数据API 产品的高并发实践 心知天气作为国内领先的商业气象服务提供商,天气数据API 产品从公司创立以来就一直扮演着很重要的角色.2009 年API 产品初次上线,历经十年,我们不断用心迭代 ...
- .NET MVC同页面显示从不同数据库(mssql、mysql)的数据
控制器: private readonly VipViewModel _model = new VipViewModel(); public static string Msg;// GET: Sys ...
- PHP解决网站大数据大流量与高并发
1:硬件方面 普通的一个p4的服务器每天最多能支持10万左右的IP,如果访问量超过10W那么需要专用的服务器才能解决,如果硬件不给力软件怎么优化都是于事无补的.主要影响服务器的速度 有:网络-硬盘读写 ...
- MySQL 高级性能优化架构 千万级高并发交易一致性系统基础
一.MySQL体系架构 由图,可以看出MySQL最上层是连接组件.下面服务器是由连接池.管理服务和工具组件.SQL接口.查询解析器.查询优化器.缓存.存储引擎.文件系统组成. 1.连接池 管理.缓冲用 ...
- PHP 网站大数据大流量与高并发 笔记
前端: 1.域名开启cdn 2.大文件使用oss php: 1.模板编译缓存 服务器: 1.负载均衡 数据库: 1.读写分离 待完善
- php如何处理大数据高并发
大数据解决方案 使用缓存: 使用方式:1,使用程序直接保存到内存中.主要使用Map,尤其ConcurrentHashMap. 使用缓存框架.常用的框架:Ehcache,Memcache,Redis等. ...
- redis作为mysql的缓存服务器(读写分离,通过mysql触发器实现数据同步)
一.redis简介Redis是一个key-value存储系统.和Memcached类似,为了保证效率,数据都是缓存在内存中.区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录 ...
- 【Redis 向Redis中批量导入mysql中的数据(亲自测试)】
转自:https://blog.csdn.net/kenianni/article/details/84910638 有改动,仅供个人学习 问题提出:缓存的冷启动问题 应用系统新版本上线,这时候 re ...
随机推荐
- 【SQL Server数据迁移】64位的机器:SQL Server中查询ORACLE的数据
从SQL Server中查询ORACLE中的数据,可以在SQL Server中创建到ORACLE的链接服务器来实现的,但是根据32位 .64位的机器和软件, 需要用不同的驱动程序来实现. 在64位的机 ...
- linux BufferedImage.createGraphics()卡住不动
项目应用服务器tomcat7,在开发(windows).测试环境(linux 64bit)均正常.在生产环境(linux 64bit)一直启动不起来,也没有报错. 最终定位问题:执行到buffered ...
- 【图解】cpu,内存,硬盘,指令的关系
1 程序员用高级语言编写程序. 2 经过编译 链接等形成机器语言的EXE文件. 3 EXE文件保持在磁盘的某个或多个扇区内 4 程序运行是在内存中生成EXE的副本 5 将指令读入cpu的寄存器 6 由 ...
- iOS - Base64转图片&&图片转Base64
记录一个小功能 app传base64位上去,服务器拿到后转图片保存,当app请求拿回用户图片时,服务器再把图片转base64字符串返回给app,app再转图片 // 64base字符串转图片 - (U ...
- MySQL连接使用
在mysql查询中,我们会通过排序,分组等在一张表中读取数据,这是比较简单的,但是在真正的应用中经常需要从多个数据表中读取数据.下面就为大家介绍这种方式,链接查询join. INNER JOIN(内连 ...
- spring boot 简要常用配置
# 激活开发环境 spring.profiles.active=dev spring.mvc.date-format=yyyy-MM-dd HH:mm:ss spring.http.encoding. ...
- AIR面向IOS设备的原生扩展
来源:http://www.cnblogs.com/alex-tech/archive/2012/03/22/2411264.html ANE组成部分 在IOS平台中,ANE的组成部分基本分为AS 3 ...
- iOS编程——Objective-C KVO/KVC机制
来源:http://blog.sina.com.cn/s/blog_b0c59541010151s0.html 这两天在看和这个相关的的内容,全部推翻重写一个版本,这是公司内做技术分享的文档总结,对结 ...
- 跨服务器查询sql语句样例(转)
若2个数据库在同一台机器上: insert into DataBase_A..Table1(col1,col2,col3----) select col11,col22,col33-- from Da ...
- 迷你商城后台管理系统————stage2核心代码实现
应用程序主函数接口 @SpringBootApplication(scanBasePackages = {"org.linlinjava.litemall.db", "o ...