Redis Study Notes (7)-cluster client (jedis) code example, redisjedis

Source: Internet
Author: User

Redis Study Notes (7)-cluster client (jedis) code example, redisjedis

In the previous section, I learned how to build a cluster and operate on the redis-cli terminal. However, a more common scenario is to read and write the cluster in the program code, this requires redis-client Support for the cluster mode. Currently, spring-data-redis (1.6.4) does not support cluster, and the latest 1.7.0 RC1 has implemented cluster, however, it has not yet been officially released, so if you want to use redis-cluster at this stage, it is best to use the native jedis for the client. The sample code is as follows:

Configuration 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"       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">    <bean id="jedisCluster" class="redis.clients.jedis.JedisCluster">        <constructor-arg index="0">            <set>                <bean class="redis.clients.jedis.HostAndPort">                    <constructor-arg name="host" value="127.0.0.1"/>                    <constructor-arg name="port" value="7000"/>                </bean>                <bean class="redis.clients.jedis.HostAndPort">                    <constructor-arg name="host" value="127.0.0.1"/>                    <constructor-arg name="port" value="7001"/>                </bean>                <bean class="redis.clients.jedis.HostAndPort">                    <constructor-arg name="host" value="127.0.0.1"/>                    <constructor-arg name="port" value="7002"/>                </bean>                <!--<bean class="redis.clients.jedis.HostAndPort">-->                    <!--<constructor-arg name="host" value="127.0.0.1"/>-->                    <!--<constructor-arg name="port" value="7003"/>-->                <!--</bean>-->                <!--<bean class="redis.clients.jedis.HostAndPort">-->                    <!--<constructor-arg name="host" value="127.0.0.1"/>-->                    <!--<constructor-arg name="port" value="7004"/>-->                <!--</bean>-->                <!--<bean class="redis.clients.jedis.HostAndPort">-->                    <!--<constructor-arg name="host" value="127.0.0.1"/>-->                    <!--<constructor-arg name="port" value="7005"/>-->                <!--</bean>-->            </set>        </constructor-arg>    </bean></beans>

Note: The above nodes do not need to be fully configured. At least the node information in one cluster can be retained. during runtime, jedis will automatically discover other nodes, but to prevent a node from being suspended, therefore, we recommend that you configure more nodes to ensure that at least one node in the heap can be connected.

Sample Code:

Package com. cnblogs. yjmyzz. redis; import org. slf4j. logger; import org. slf4j. loggerFactory; import org. springframework. context. applicationContext; import org. springframework. context. support. classPathXmlApplicationContext; import redis. clients. jedis. jedisCluster; import redis. clients. jedis. jedisPool; import java. util. list; import java. util. map; import java. util. set; public class AppDemo {private static Logger Logger = LoggerFactory. getLogger (AppDemo. class); private static JedisCluster jc = null; private static final String KEYS_STRING = "STRING"; private static final String KEYS_SET = "SET"; private static final String KEYS_LIST = "LIST "; private static final String KEYS_HASH = "HASH"; private static final String KEYS_ZSET = "ZSET"; private static void addKey (final String conainter, final String key) {If (! Jc. exists (conainter) {jc. sadd (conainter, key);} else {if (! Jc. smembers (conainter ). contains (key) {jc. sadd (conainter, key) ;}}/*** write String cache ** @ param key * @ param value * @ return */private static String set (final String key, final String value) {String result = jc. set (key, value); addKey (KEYS_STRING, key); return result ;} /*** write to Set cache ** @ param key * @ param member * @ return */private static Long sadd (final String key, final String... member) {L Ong result = jc. sadd (key, member); addKey (KEYS_SET, key); return result ;} /*** write List from the left ** @ param key * @ param string * @ return */private static Long lpush (final String key, final String... string) {Long result = jc. lpush (key, string); addKey (KEYS_LIST, key); return result ;} /*** write to HashMap cache ** @ param key * @ param field * @ param value * @ return */private static Long hset (final String key, Final String field, final String value) {Long result = jc. hset (key, field, value); addKey (KEYS_HASH, key); return result ;} /*** write ZSet cache ** @ param key * @ param score * @ param member * @ return */private static Long zadd (final String key, final double score, final String member) {Long result = jc. zadd (key, score, member); addKey (KEYS_ZSET, key); return result;} private static Long zadd (fina L String key, final String member) {Long result = jc. zadd (key, 0d, member); addKey (KEYS_ZSET, key); return result;} public static void main (String [] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext ("spring-redis.xml"); jc = ctx. getBean (JedisCluster. class); Map <String, JedisPool> nodes = jc. getClusterNodes (); for (Map. entry <String, JedisPool> entry: nodes. entrySet () {logger. Info (entry. getKey () + "=>" + entry. getValue (). toString (); // clear all data. try {entry. getValue (). getResource (). flushDB ();} catch (Exception e) {logger.info (e. getLocalizedMessage (); // an error is returned when flushDB is executed on the slave node.} // entry. getValue (). getResource (). keys ("*"); // use with caution. A large number of caches may cause performance problems .} // check whether the key has logger.info (jc. exists (""). toString (); // string write test logger.info (set ("a", "hello world! "); Logger.info (set (" B "," hello redis! "); // String read Test logger.info (jc. get ("a"); // set write operation logger.info ("set write test =>"); logger.info (sadd ("set1", "", "B", "c") + ""); // test logger.info (jc. type ("set1"); // set read Test logger.info ("set read test =>"); Set <String> set1 = jc. smembers ("set1"); for (String s: set1) {logger.info (s);} // list write test logger.info ("list write test => "); logger.info (lpush ("list1", "1", "2", "3") + ""); // list read Test logger.info ("list read test =>"); List <String> list1 = jc. lrange ("list1", 0,999); for (String s: list1) {logger.info (s) ;}// test logger.info ("hash write test => "); logger.info (hset ("hash1", "jimmy", "Yang junming") + ""); logger.info (hset ("hash1", "CN", "China ") + ""); logger.info (hset ("hash1", "US", "US") + ""); // hash read Test logger.info ("hash read test =>"); Map <String, String> hash1 = jc. hgetAll ("hash1"); for (Map. entry <String, String> entry: hash1.entrySet () {logger.info (entry. getKey () + ":" + entry. getValue ();} // zset write test logger.info ("zset write test =>"); logger.info (zadd ("zset1", "3") + ""); logger.info (zadd ("zset1", "2") + ""); logger.info (zadd ("zset1", "1") + ""); logger.info (zadd ("zset1", "4") + ""); logger.info (zadd ("zset1", "5") + ""); logger.info (zadd ("zset1", "6") + "); // zset read Test logger.info (" zset read Test ==> "); set <String> zset1 = jc. zrange ("zset1", 0,999); for (String s: zset1) {logger.info (s );} // traverse the key logger.info of all cache items ("traverse all keys in the cluster ==>"); logger.info (jc. smembers (KEYS_STRING ). toString (); logger.info (jc. smembers (KEYS_HASH ). toString (); logger.info (jc. smembers (KEYS_SET ). toString (); logger.info (jc. smembers (KEYS_LIST ). toString (); logger.info (jc. smembers (KEYS_ZSET ). toString ());}}

Note: We recommend that you avoid using jedis to perform a fuzzy search on the nodes. If many cached items exist, this operation may result in a sharp decline in redis performance. The improvement is to create a set by yourself, record all cached keys. For details, refer to the above method. In addition, jedis provides a large number of commands, but there is no detailed documentation (estimated, the author thinks the code is the best document), you can guess from the method prefix, for example, sXXX indicates the Set operation, hXXX indicates the hash operation, lXXX or rXXX indicates the list operation, zXXX indicates the zset operation, and no prefix exists, for example, set/get is a string operation.

Some netizens sorted out a document for the operation of jedis, see: http://blog.csdn.net/zhu_xun/article/details/16806285

Finally, add the source code of the above example: https://github.com/yjmyzz/redis-cluster-demo

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.