Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
mate0021 committed Mar 10, 2022
1 parent 400e537 commit 4ff6726
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,15 @@
import com.redislabs.university.RU102J.script.CompareAndUpdateScript;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Transaction;

import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Map;

import static com.redislabs.university.RU102J.api.SiteStats.*;

public class SiteStatsDaoRedisImpl implements SiteStatsDao {

private final int weekSeconds = 60 * 60 * 24 * 7;
Expand Down Expand Up @@ -47,16 +50,16 @@ public void update(MeterReading reading) {
ZonedDateTime day = reading.getDateTime();
String key = RedisSchema.getSiteStatsKey(siteId, day);

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

// A naive implementation of update. This implementation has
// potential race conditions and makes several round trips to Redis.
private void updateBasic(Jedis jedis, String key, MeterReading reading) {
String reportingTime = ZonedDateTime.now(ZoneOffset.UTC).toString();
jedis.hset(key, SiteStats.reportingTimeField, reportingTime);
jedis.hincrBy(key, SiteStats.countField, 1);
jedis.hset(key, reportingTimeField, reportingTime);
jedis.hincrBy(key, countField, 1);
jedis.expire(key, weekSeconds);

String maxWh = jedis.hget(key, SiteStats.maxWhField);
Expand All @@ -81,6 +84,18 @@ 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();
try (Transaction transaction = jedis.multi()) {
transaction.hset(key, reportingTimeField, reportingTime);
transaction.hincrBy(key, countField, 1);
transaction.expire(key, weekSeconds);

compareAndUpdateScript.updateIfGreater(transaction, key, maxWhField, reading.getWhGenerated());
compareAndUpdateScript.updateIfLess(transaction, key, minWhField, reading.getWhGenerated());
compareAndUpdateScript.updateIfGreater(transaction, key, maxCapacityField, getCurrentCapacity(reading));

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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ public void flush() {
}

@Test
@Ignore
public void homework23() {
jedis.set("a", "foo");
jedis.set("b", "bar");
Expand Down

0 comments on commit 4ff6726

Please sign in to comment.