Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Optimized and correct implementation of update() for SiteStatsDaoRedisImpl.java.
1. Use Transaction wherever you can.
2. Perform the compare-and-update operations using Lua. The file CompareAndUpdateScript.java contains everything you need.
  • Loading branch information
J-A-I-L committed Jun 26, 2022
1 parent b8e1812 commit a262692
Showing 1 changed file with 15 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public void update(MeterReading reading) {
ZonedDateTime day = reading.getDateTime();
String key = RedisSchema.getSiteStatsKey(siteId, day);

updateBasic(jedis, key, reading);
updateOptimized(jedis, key, reading);
}
}

Expand Down Expand Up @@ -81,6 +81,20 @@ private void updateBasic(Jedis jedis, String key, MeterReading reading) {
// Challenge #3
private void updateOptimized(Jedis jedis, String key, MeterReading reading) {
// START Challenge #3
String reportingTime = ZonedDateTime.now(ZoneOffset.UTC).toString();

Transaction t = jedis.multi();
CompareAndUpdateScript script = new CompareAndUpdateScript(jedisPool);

t.hset(key, SiteStats.reportingTimeField, reportingTime);
t.hincrBy(key, SiteStats.countField, 1);
t.expire(key, weekSeconds);

script.updateIfGreater(t, key, SiteStats.maxWhField, reading.getWhGenerated());
script.updateIfLess(t, key, SiteStats.minWhField, reading.getWhGenerated());
script.updateIfGreater(t, key, SiteStats.maxCapacityField, getCurrentCapacity(reading));

t.exec();
// END Challenge #3
}

Expand Down

0 comments on commit a262692

Please sign in to comment.