I had to use redis in our project in both python and Java. In this post I will cover a basic example of generating counters using Redis. I had to use cassandra db to push data but cassandra doesnt have autoincrement counters at this moment so we will use redis till the new version of cassandra supports it. Redis has memcache like API but the advantage is that its has atomic operations and the data is saved so server restarts will survive the data. The only disadvantage I see is that the java client yet doesnt support consistent hashing but eventually it will.
- Install the redis server by following http://code.google.com/p/redis/wiki/QuickStart
- run it using ./redis-server
- Download JRedis client from http://github.com/alphazero/jredis/downloads
- Run the below program.
import org.jredis.JRedis;
import org.jredis.RedisException;
import org.jredis.connector.ConnectionSpec;
import org.jredis.ri.alphazero.JRedisService;
import org.jredis.ri.alphazero.connection.DefaultConnectionSpec;
public class RedisCounterService {
private String host;
private int port;
private int connectionCount = 3;
private JRedis jredis;
public void setHost(String host) {
this.host = host;
}
public void setPort(int port) {
this.port = port;
}
public void setConnectionCount(int connectionCount) {
this.connectionCount = connectionCount;
}
public void init() {
ConnectionSpec connectionSpec = DefaultConnectionSpec.newSpec(host, port, 0, null);
/*This is a connection pool*/
jredis = new JRedisService(connectionSpec, connectionCount);
}
public Long getNextRevisionNumber(String counterName) throws RedisException {
//Redis API is thread safe so you dont need to synchronize
long nextRevisionNumber = jredis.incr(counterName);
return nextRevisionNumber;
}
public static void main(String []args) throws Exception {
RedisCounterService redis = new RedisCounterService();
redis.setHost("localhost");
redis.setPort(6379);
redis.init();
String counter = "test" + System.currentTimeMillis();
System.out.println(1==redis.getNextRevisionNumber(counter));
System.out.println(2==redis.getNextRevisionNumber(counter));
System.out.println(3==redis.getNextRevisionNumber(counter));
System.out.println(1==redis.getNextRevisionNumber(counter + "new"));
}
}
Am also going to take a look at NoSQL storages..Cassandra sounds good thing to start from on this field.
ReplyDeleteYou we use cassandra also. I use hector api v2 to connect to cassandra, was going to write a beginer article for that also but somehow didnt got time.
ReplyDelete