同步mysql数据库到codis缓存中
public void syncRule() { // 根据时间戳获取Mycat中规则表数据 logger.info("start ..."); String sql = ""; // 若最后一次同步时间为空,则按最后更新时间排序,取最小的时间作为当前时间戳 if (ruleCurrentTimestamp != null) { sql = "select * from t_table where update_date >" + ruleCurrentTimestamp + " order by update_date limit 10"; } else { sql = "select * from t_table order by update_date limit 10"; } // 升序会将最后一次的时间也就是最大的时间作为当前的currentTimeStamp jdbcTemplate.query(sql, new Object[] {}, new RowMapper<String>() { public String mapRow(ResultSet result, int rowNum) throws SQLException { ruleCurrentTimestamp = result.getLong("update_date"); return result.getString("rule_code"); } }); // objs 即是Mycat里面查询出来需要同步的数据 List<JSONObject> objs = jdbcTemplate.query(sql, new Object[] {}, new RowMapper<JSONObject>() { public JSONObject mapRow(ResultSet result, int rowNum) throws SQLException { int c = result.getMetaData().getColumnCount(); JSONObject obj = new JSONObject(); for (int t = 1; t <= c; t++) { if (result.getObject(t) == null) { continue; } else { obj.put(result.getMetaData().getColumnLabel(t).toLowerCase(), result.getObject(t)); } } return obj; } }); /** * 将风控事件表的rule_code作为key ,该条数据作为value,写入Codis中 */ try { for (JSONObject obj : objs) { logger.info(obj.get("rule_code").toString()); jedis.set(obj.get("rule_code").toString(), obj.toJSONString()); } logger.info("同步到Codis成功!!!"); rulePreviousTimestamp = ruleCurrentTimestamp; // 将写入成功后的时间写到zookeeper中 zkClient.writeData(Constant.RULE_TIMESTAMP_PATH, String.valueOf(ruleCurrentTimestamp)); } catch (Exception e) { logger.info("同步到Codis失败!!!"); ruleCurrentTimestamp = rulePreviousTimestamp; logger.error(e.getMessage(), e); } }