沃梦达 / 编程技术 / 数据库 / 正文

Jedis操作Redis

Jedis操作单机版RedisJedis jedis = new Jedis(ip,port);//创建一个Jedis对象jedis.set(“test”,“hello world”);//存值String s = jedis.get(“test”);//取值System.out.println(s);jedis.clo...

 Jedis操作单机版Redis

Jedis jedis = new Jedis(ip,port);//创建一个Jedis对象

jedis.set(“test”,“hello world”);//存值

String s = jedis.get(“test”);//取值

System.out.println(s);

jedis.close();//一定要记得关闭,因为它不会自动关闭,极为浪费资源

 

使用连接池

JedisPool jedisPool = new JedisPool(ip,port); 

Jedis jedis =  jedisPool.getResource();

jedis.set(“test”,“hello world”);//存值

String s = jedis.get(“test”);//取值

System.out.println(s);

jedis.close();//一定要记得关闭,不然连接池无法回收;

jedisPool.close();//系统关闭时关闭连接池、、

 

Jedis操作集群版Redis//cluster意为集群,一群

Set<HostAndPort> nodes = new HashSet();

nodes.add(new HostA
ndPort(ip,port));//每一个Redis服务器就添加一个节点

JedisCluster jedisCluster = new JedisCluster(nodes);

jedisCluster.set("key","value");

jedisCluster.get("key");

jedisCluster.close();//系统关闭时关闭

通过spring配置

单机版

配置实现类

<bean id = "jedisClientSingle" class=“实现类名”/>

集群版配置

<bean id = ""jedisCluster" class=“redis.clients.h=jedis.JedisCluster”>

<constructor-arg>

<set>

<bean class=""redis.clients.jedis.HostAndPort>

<constructor-arg name = "host" value="ip"/>

<constructor-arg name = "port" value="port"/>

</bean>

<bean class=""redis.clients.jedis.HostAndPort>

<constructor-arg name = "host" value="ip"/>

<constructor-arg name = "port" value="port"/>

</bean>

</set>

</costructor-arg>

</bean>

 

通过Spring容器获取JedisCluster对象

ApplicationContext applicationContext = newClassPathXmlAppolicationContext(“classpath:applicationContext.xml”);

 JedisCluster jedisCluster = applicationContext.getBean(JedisCluster.class);

jedisCluster.set("key","value");

jedisCluster.get("key");

jedisCluster.close();//系统关闭时关闭

 

本文标题为:Jedis操作Redis

基础教程推荐