Hello All,
In redis entire data set, like memcached, is stored in-memory so it is extremely fast (like memcached)… often even faster than memcached. Redis had virtual memory, where rarely used values would be swapped out to disk, so only the keys had to fit into memory, but this has been deprecated. Going forward the use cases for Redis are those where its possible (and desirable) for the entire data set to fit into memory.
Redis is a fantastic choice if you want a highly scalable data store shared by multiple processes, multiple applications, or multiple servers. As just an inter-process communication mechanism it is tough to beat. The fact that you can communicate cross-platform, cross-server, or cross-application just as easily makes it a pretty great choice for many many use cases. Its speed also makes it great as a caching layer.
You can use below link to learn the basic of Redis. This is superb link
wget http://download.redis.io/redis-stable.tar.gztar xvzf redis-stable.tar.gzcd redis-stablemake
if got exception “make[3]: *** [net.o] Error 127” during make. Use below command
make distclean
apt-get install gcc
then again run make commond
After the compilation the src directory inside the Redis distribution is populated with the different executables that are part of Redis
- redis-server is a redis server itself.
- redis-cli is the command line interface utility to talk with Redis.
- redis-benchmark is used to check redis performance
- redis-check-aof and redis-check-dump are useful in rare event of corrupted data files.
Copy both Redis server than the command line interface in proper places using the following commands:
sudo cp redis-server /usr/local/bin/
sudo cp redis-cli /usr/local/bin/
sudo cp redis-benchmark /usr/local/bin/
Install Redis in your Linux box in a proper way using an init script, so that after a restart everything will start again properly.
Create a directory where to store your Redis config files and your data:
sudo mkdir /etc/redis sudo mkdir /var/redis
Copy the init script that you’ll find in the Redis distribution under the utils directory into /etc/init.d. We suggest calling it with the name of the port where you are running this instance of Redis. For example:
sudo cp utils/redis_init_script /etc/init.d/redis_6379
Edit the init script.
sudo vi /etc/init.d/redis_6379
Make sure to modify REDIS_PORT accordingly to the port you are using. Both the pid file path and the configuration file name depend on the port number. Copy the template configuration file you’ll find in the root directory of the Redis distribution into /etc/redis/ using the port number as name, for instance:
sudo cp redis.conf /etc/redis/6379.conf
Create a directory inside /var/redis that will work as data and working directory for this Redis instance:
sudo mkdir /var/redis/6379
Edit the configuration file, making sure to perform the following changes: Set daemonize to yes (by default it is set to no).
Set the pidfile to /var/run/redis_6379.pid (modify the port if needed). Change the port accordingly. In our example it is not needed as the default port is already 6379. Set your preferred loglevel. Set the logfile to /var/log/redis_6379.log
Set the dir to /var/redis/6379 (very important step!). Finally add the new Redis init script to all the default runlevels using the following command:
sudo update-rc.d redis_6379 defaults
You are done! Now you can try running your instance with:
/etc/init.d/redis_6379 start
Make sure that everything is working as expected:
Try pinging your instance with redis-cli. Do a test save with redis-cli save and check that the dump file is correctly stored into /var/redis/6379/ (you should find a file called dump.rdb).
Check that your Redis instance is correctly logging in the log file. If it’s a new machine where you can try it without problems make sure that after a reboot everything is still working.
We can also do a quick check by running the Redis Benchmark. It will not only stress test Redis itself but also verify that there’s nothing wrong with our installation. The following will issue 100.000 requests from 50 clients sending 12 commands at the same time.
$ redis-benchmark -q -n 100000 -c 50 -P 12
For advanced configuration you can visit below link
Working with java
There are many redis library available for java. Jedis, JDBC-Redis and JRedis . I did some reading and found out that jedis is a better Java client for Redis. I tried it out and it works perfectly and it is also very simple to use.
I am going to create a example for jedis. Now create a java project in eclipse ide and put the name JavaRedisExample.
Step 1 : Create a fresh java project JavaRedisExample
Step2 : Create a package com.redis.manager
Step3 : Create a java class RedisManager
package com.redis.manager;
/*
* Author: radhey
* Date: 21-Dec-2013
* Last Date of Modification: 21-Dec-2013 1:36:37 PM
* Comments:
* Version: 1.0
*
*/
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisManager {
private static final RedisManager instance = new RedisManager();
private static JedisPool pool;
private RedisManager() {}
public final static RedisManager getInstance() {
return instance;
}
public void connect() {
// Create and set a JedisPoolConfig
JedisPoolConfig poolConfig = new JedisPoolConfig();
// Maximum active connections to Redis instance
poolConfig.setMaxActive(20);
// Tests whether connection is dead when connection
// retrieval method is called
poolConfig.setTestOnBorrow(true);
/* Some extra configuration */
// Tests whether connection is dead when returning a
// connection to the pool
poolConfig.setTestOnReturn(true);
// Number of connections to Redis that just sit there
// and do nothing
poolConfig.setMaxIdle(5);
// Minimum number of idle connections to Redis
// These can be seen as always open and ready to serve
poolConfig.setMinIdle(1);
// Tests whether connections are dead during idle periods
poolConfig.setTestWhileIdle(true);
// Maximum number of connections to test in each idle check
poolConfig.setNumTestsPerEvictionRun(10);
// Idle connection checking period
poolConfig.setTimeBetweenEvictionRunsMillis(60000);
// Create the jedisPool
pool = new JedisPool(poolConfig, "localhost", 6379);
}
public void release() {
pool.destroy();
}
public Jedis getJedis() {
return pool.getResource();
}
public void returnJedis(Jedis jedis) {
pool.returnResource(jedis);
}
}
Step 4: Create a test package com.redis.test and then create a java class RedisTest
/* * Author: radhey * Date: 21-Dec-2013 * Last Date of Modification: 21-Dec-2013 1:36:37 PM * Comments: * Version: 1.0 * */ package com.redis.test; import redis.clients.jedis.Jedis; import com.redis.manager.RedisManager; public class RedisTest { public static void main(String[] args) { RedisManager.getInstance().connect(); Jedis jedis = RedisManager.getInstance().getJedis(); jedis.set("name", "radhey"); String val = jedis.get("name"); System.out.println(val); RedisManager.getInstance().release(); } }
Step 5 : You need jedis library for this test project. You can download the same from below git repository.
Redis with Spring
Step1 : create a maven project named “SpringRedisExample”
Step2 : add dependency in pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>SpringRedisExample</groupId>
<artifactId>SpringRedisExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceencoding>UTF-8</project.build.sourceencoding>
<spring.version>3.1.0.RELEASE</spring.version>
</properties>
<build>
<sourceDirectory>src</sourceDirectory>
<resources>
<resource>
<directory>config</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.0.0</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
</project>
Step 3 : Create a resource folder and named it config. Then create a property file redis.properties
redis.serverHost=localhost redis.serverPort=6379 redis.password=
Then create a redisConfig.xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:redis.properties"/>
<bean id="connectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="${redis.serverHost}" p:port="${redis.serverPort}" p:password="${redis.password}" />
<!-- redis template -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
p:connection-factory-ref="connectionFactory" />
<context:annotation-config />
<bean id="example" class="com.test.redis.Example">
<property name="redisTemplate" ref="redisTemplate"/>
</bean>
</beans>
Step 4: Create a test class Example.java
/*
* Author: radhey
* Date: 21-Dec-2013
* Last Date of Modification: 21-Dec-2013 4:03:28 PM
* Comments:
* Version: 1.0
*
*/
package com.test.redis;
import java.net.MalformedURLException;
import java.net.URL;
import org.springframework.data.redis.core.RedisTemplate;
public class Example {
private RedisTemplate<String, String> redisTemplate;
public RedisTemplate<String, String> getRedisTemplate() {
return redisTemplate;
}
public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
this.redisTemplate = redisTemplate;
}
public void addLink(String userId, URL url) {
redisTemplate.boundListOps(userId).leftPush(url.toExternalForm());
}
public URL getLink(String userId) {
try {
URL url = new URL(redisTemplate.boundListOps(userId).rightPop());
return url;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Then create a test class HelloWorld.java
package com.test.redis;
import java.net.MalformedURLException;
import java.net.URL;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloWorld {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"redisConfig.xml");
Example eg = (Example) applicationContext.getBean("example");
try {
URL url = new URL("http://localhost:8888");
eg.addLink("local", url);
URL url1 = eg.getLink("local");
System.out.println(url1.toString());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Step 5: Run the class HelloWorld. You will get below result
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
http://localhost:8888
you can download this example from the https://github.com/itthought/noSQL-Test/tree/master/RedisExample

