Search in sources :

Example 11 with StopWatch

use of com.rdbcache.models.StopWatch in project rdbcache by rdbcache.

the class ExpireOps method onExpireEvent.

/**
 * To process key expired event
 *
 * @param event key expired event
 */
public void onExpireEvent(String event) {
    LOGGER.debug("Received: " + event);
    if (!event.startsWith(eventPrefix)) {
        return;
    }
    String[] parts = event.split("::");
    if (parts.length < 3) {
        LOGGER.error("invalid event format");
        return;
    }
    String key = parts[1];
    String traceId = parts[2];
    Context context = new Context(traceId);
    KvPair pair = new KvPair(key);
    if (enableMonitor)
        context.enableMonitor(event, "event", key);
    String lockKey = "lock_" + eventPrefix + "::" + key + "::" + traceId;
    String signature = Utils.generateId();
    StopWatch stopWatch = context.startStopWatch("redis", "scriptExecutor.execute");
    String result = scriptExecutor.execute(expire_event_lock_script, Collections.singletonList(lockKey), signature, eventLockTimeout.toString());
    if (stopWatch != null)
        stopWatch.stopNow();
    if (!result.equals("OK")) {
        String msg = "unable to lock key: " + lockKey;
        LOGGER.trace(msg);
        context.closeMonitor();
        return;
    }
    try {
        KvPairs pairs = new KvPairs(pair);
        AnyKey anyKey = new AnyKey();
        if (!AppCtx.getKeyInfoRepo().find(context, pairs, anyKey)) {
            String msg = "keyInfo not found";
            LOGGER.error(msg);
            context.logTraceMessage(msg);
            return;
        }
        KeyInfo keyInfo = anyKey.getKeyInfo();
        LOGGER.trace(keyInfo.toString());
        Long expire = Long.valueOf(keyInfo.getExpire());
        if (expire > 0) {
            if (AppCtx.getRedisRepo().find(context, pairs, anyKey)) {
                AppCtx.getDbaseRepo().save(context, pairs, anyKey);
                AppCtx.getRedisRepo().delete(context, pairs, anyKey);
                AppCtx.getKeyInfoRepo().delete(context, pairs);
            } else {
                String msg = "failed to find key from redis for " + key;
                LOGGER.error(msg);
                context.logTraceMessage(msg);
            }
        }
        if (expire < 0) {
            if (AppCtx.getDbaseRepo().find(context, pairs, anyKey)) {
                AppCtx.getRedisRepo().save(context, pairs, anyKey);
                setExpireKey(context, pairs, anyKey);
            } else {
                String msg = "failed to find key from database for " + key;
                LOGGER.error(msg);
                context.logTraceMessage(msg);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        String msg = e.getCause().getMessage();
        LOGGER.error(msg);
        context.logTraceMessage(msg);
    } finally {
        stopWatch = context.startStopWatch("redis", "scriptExecutor.execute");
        scriptExecutor.execute(expire_event_unlock_script, Collections.singletonList(lockKey), signature);
        if (stopWatch != null)
            stopWatch.stopNow();
        context.closeMonitor();
    }
}
Also used : KvPair(com.rdbcache.models.KvPair) KeyInfo(com.rdbcache.models.KeyInfo) StopWatch(com.rdbcache.models.StopWatch)

Example 12 with StopWatch

use of com.rdbcache.models.StopWatch in project rdbcache by rdbcache.

the class Query method executeInsert.

public boolean executeInsert(boolean enableLocal, boolean enableRedis) {
    params = new ArrayList<>();
    boolean allOk = true;
    for (int i = 0; i < pairs.size(); i++) {
        KvPair pair = pairs.get(i);
        KeyInfo keyInfo = anyKey.getAny(i);
        String table = keyInfo.getTable();
        Map<String, Object> map = pair.getData();
        String autoIncKey = AppCtx.getDbaseOps().getTableAutoIncColumn(context, table);
        boolean cacheUpdate = false;
        if (!map.containsKey(autoIncKey) && keyInfo.getParams() != null && keyInfo.getParams().size() == 1) {
            String stdClause = "(" + autoIncKey + " = ?)";
            if (stdClause.equals(keyInfo.getClause())) {
                map.put(autoIncKey, keyInfo.getParams().get(0));
                cacheUpdate = true;
            }
        }
        Map<String, Object> columns = keyInfo.getColumns();
        AppCtx.getDbaseOps().convertDbMap(columns, map);
        String fields = "", values = "";
        params.clear();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            params.add(entry.getValue());
            if (fields.length() != 0) {
                fields += ", ";
                values += ", ";
            }
            fields += entry.getKey();
            values += "?";
        }
        sql = "insert into " + table + " (" + fields + ") values (" + values + ")";
        LOGGER.trace("sql: " + sql);
        LOGGER.trace("params: " + params.toString());
        int rowCount = 0;
        KeyHolder keyHolder = new GeneratedKeyHolder();
        StopWatch stopWatch = context.startStopWatch("dbase", "jdbcTemplate.update");
        try {
            rowCount = jdbcTemplate.update(new PreparedStatementCreator() {

                @Override
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement ps;
                    ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                    int i = 1;
                    for (Object param : params) {
                        ps.setObject(i++, param);
                    }
                    return ps;
                }
            }, keyHolder);
            if (stopWatch != null)
                stopWatch.stopNow();
        } catch (Exception e) {
            if (stopWatch != null)
                stopWatch.stopNow();
            allOk = false;
            String msg = e.getCause().getMessage();
            LOGGER.error(msg);
            context.logTraceMessage(msg);
            if (context.isSync()) {
                throw new ServerErrorException(context, msg);
            }
        }
        if (rowCount > 0) {
            if (autoIncKey != null && keyHolder.getKey() != null) {
                String keyValue = String.valueOf(keyHolder.getKey());
                map.put(autoIncKey, keyValue);
                cacheUpdate = true;
            }
            if (cacheUpdate) {
                if (enableLocal) {
                    AppCtx.getLocalCache().putData(pair, keyInfo);
                }
                if (enableRedis) {
                    AppCtx.getRedisRepo().save(context, new KvPairs(pair), new AnyKey(keyInfo));
                }
            }
            if (!Parser.prepareStandardClauseParams(context, pair, keyInfo)) {
                String msg = "executeInsert failed when prepareStandardClauseParams for " + pair.getId();
                LOGGER.error(msg);
                context.logTraceMessage(msg);
                if (context.isSync()) {
                    throw new ServerErrorException(context, msg);
                }
            }
            LOGGER.trace("inserted " + pair.getId() + " into " + table);
        } else {
            allOk = false;
            LOGGER.warn("failed to insert " + pair.getId() + " into " + table);
        }
    }
    return allOk;
}
Also used : AnyKey(com.rdbcache.helpers.AnyKey) KvPair(com.rdbcache.models.KvPair) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) KvPairs(com.rdbcache.helpers.KvPairs) KeyHolder(org.springframework.jdbc.support.KeyHolder) GeneratedKeyHolder(org.springframework.jdbc.support.GeneratedKeyHolder) ServerErrorException(com.rdbcache.exceptions.ServerErrorException) SQLException(java.sql.SQLException) StopWatch(com.rdbcache.models.StopWatch) GeneratedKeyHolder(org.springframework.jdbc.support.GeneratedKeyHolder) KeyInfo(com.rdbcache.models.KeyInfo) PreparedStatementCreator(org.springframework.jdbc.core.PreparedStatementCreator) ServerErrorException(com.rdbcache.exceptions.ServerErrorException)

Example 13 with StopWatch

use of com.rdbcache.models.StopWatch in project rdbcache by rdbcache.

the class Query method executeDelete.

public boolean executeDelete() {
    boolean allOk = true;
    for (int i = 0; i < pairs.size(); i++) {
        KvPair pair = pairs.get(i);
        KeyInfo keyInfo = anyKey.getAny(i);
        String table = keyInfo.getTable();
        if (!keyInfo.getIsNew() && !keyInfo.hasParams() && keyInfo.ifJustCreated()) {
            waitForParamsUpdate(pair.getId(), keyInfo);
        }
        if (!Parser.prepareStandardClauseParams(context, pair, keyInfo)) {
            String msg = "executeDelete failed when calling prepareStandardClauseParams for " + pair.getId();
            LOGGER.error(msg);
            context.logTraceMessage(msg);
            if (context.isSync()) {
                throw new ServerErrorException(context, msg);
            }
            continue;
        }
        params = keyInfo.getParams();
        String clause = keyInfo.getClause();
        sql = "delete from " + table + " where " + clause + " limit 1";
        LOGGER.trace("sql: " + sql);
        LOGGER.trace("params: " + params.toString());
        StopWatch stopWatch = context.startStopWatch("dbase", "jdbcTemplate.delete");
        try {
            if (jdbcTemplate.update(sql, params.toArray()) > 0) {
                if (stopWatch != null)
                    stopWatch.stopNow();
                LOGGER.trace("delete " + pair.getId() + " from " + table);
                continue;
            } else {
                if (stopWatch != null)
                    stopWatch.stopNow();
                allOk = false;
            }
        } catch (Exception e) {
            if (stopWatch != null)
                stopWatch.stopNow();
            allOk = false;
            String msg = e.getCause().getMessage();
            LOGGER.error(msg);
            context.logTraceMessage(msg);
            e.printStackTrace();
            if (context.isSync()) {
                throw new ServerErrorException(context, msg);
            }
        }
        keyInfo.setQueryKey(null);
    }
    return allOk;
}
Also used : KvPair(com.rdbcache.models.KvPair) KeyInfo(com.rdbcache.models.KeyInfo) ServerErrorException(com.rdbcache.exceptions.ServerErrorException) ServerErrorException(com.rdbcache.exceptions.ServerErrorException) SQLException(java.sql.SQLException) StopWatch(com.rdbcache.models.StopWatch)

Example 14 with StopWatch

use of com.rdbcache.models.StopWatch in project rdbcache by rdbcache.

the class Query method executeSelect.

public boolean executeSelect() {
    KeyInfo keyInfo = anyKey.getKeyInfo();
    String table = keyInfo.getTable();
    LOGGER.trace("sql: " + sql);
    LOGGER.trace("params: " + (params != null ? params.toString() : "null"));
    List<Map<String, Object>> list = null;
    StopWatch stopWatch = context.startStopWatch("dbase", "jdbcTemplate.queryForList");
    try {
        if (params != null) {
            list = jdbcTemplate.queryForList(sql, params.toArray());
        } else {
            list = jdbcTemplate.queryForList(sql);
        }
        if (stopWatch != null)
            stopWatch.stopNow();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                KvPair pair = pairs.getAny(i);
                keyInfo = anyKey.getAny(i);
                pair.setData(list.get(i));
                // 
                if (!Parser.prepareStandardClauseParams(context, pair, keyInfo)) {
                    String msg = "executeSelect failed when prepareStandardClauseParams for " + pair.getId();
                    LOGGER.error(msg);
                    context.logTraceMessage(msg);
                    if (context.isSync()) {
                        throw new ServerErrorException(context, msg);
                    }
                }
                LOGGER.trace("found " + pair.getId() + " from " + table);
            }
            return true;
        }
    } catch (Exception e) {
        if (stopWatch != null)
            stopWatch.stopNow();
        e.printStackTrace();
        String msg = e.getCause().getMessage();
        LOGGER.error(msg);
        context.logTraceMessage(msg);
        if (context.isSync()) {
            throw new ServerErrorException(context, msg);
        }
    }
    return false;
}
Also used : KeyInfo(com.rdbcache.models.KeyInfo) KvPair(com.rdbcache.models.KvPair) ServerErrorException(com.rdbcache.exceptions.ServerErrorException) ServerErrorException(com.rdbcache.exceptions.ServerErrorException) SQLException(java.sql.SQLException) StopWatch(com.rdbcache.models.StopWatch)

Aggregations

KvPair (com.rdbcache.models.KvPair)14 StopWatch (com.rdbcache.models.StopWatch)14 KeyInfo (com.rdbcache.models.KeyInfo)9 ServerErrorException (com.rdbcache.exceptions.ServerErrorException)8 SQLException (java.sql.SQLException)4 AnyKey (com.rdbcache.helpers.AnyKey)1 KvPairs (com.rdbcache.helpers.KvPairs)1 Connection (java.sql.Connection)1 PreparedStatement (java.sql.PreparedStatement)1 PreparedStatementCreator (org.springframework.jdbc.core.PreparedStatementCreator)1 GeneratedKeyHolder (org.springframework.jdbc.support.GeneratedKeyHolder)1 KeyHolder (org.springframework.jdbc.support.KeyHolder)1