redis怎么和mysql同步
展开全部
二者数据同步的关键在于mysql数据库中主键,方案是在redis启动时区mysql读取所有表键值存入redis中,往redis写数据是,对redis主键自增并进行读取,若mysql更新失败,则需要及时清除缓存及同步redis主键。
参考代码如下:
String tbname = "login";
//获取mysql表主键值--redis启动时
long id = MySQL.getID(tbname);
//设置redis主键值--redis启动时
redisService.set(tbname, String.valueOf(id));
System.out.println(id);
long l = redisService.incr(tbname);
System.out.println(l);
Login login = new Login();
login.setId(l);
login.setName("redis");
redisService.hmset(String.valueOf(login.getId()), login);
boolean b = MySQL.insert("insert into login(id,name) values(" + login.getId()
+ ",'" + login.getName() + "')");
/**
*
* 队列处理器更新mysql失败:
*
* 清除缓存数据,同时主键值自减
*/
if (!b)
{
redisService.delKeyAndDecr
(tbname, "Login:"+String.valueOf(login.getId()));
// redisService.delete("Login:"+String.valueOf(login.getId()));
//redisService.decr(tbname);
}
System.out.println(redisService.exists("Login:"+String.valueOf(login.getId())));
System.out.println(redisService.get(tbname));
参考代码如下:
String tbname = "login";
//获取mysql表主键值--redis启动时
long id = MySQL.getID(tbname);
//设置redis主键值--redis启动时
redisService.set(tbname, String.valueOf(id));
System.out.println(id);
long l = redisService.incr(tbname);
System.out.println(l);
Login login = new Login();
login.setId(l);
login.setName("redis");
redisService.hmset(String.valueOf(login.getId()), login);
boolean b = MySQL.insert("insert into login(id,name) values(" + login.getId()
+ ",'" + login.getName() + "')");
/**
*
* 队列处理器更新mysql失败:
*
* 清除缓存数据,同时主键值自减
*/
if (!b)
{
redisService.delKeyAndDecr
(tbname, "Login:"+String.valueOf(login.getId()));
// redisService.delete("Login:"+String.valueOf(login.getId()));
//redisService.decr(tbname);
}
System.out.println(redisService.exists("Login:"+String.valueOf(login.getId())));
System.out.println(redisService.get(tbname));
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |