使用Jedis連線Redis
阿新 • • 發佈:2019-01-24
使用Jedis連線redis跟我們使用jdbc連線資料庫特別向,話不多說,直接上程式碼。
需要引入的jar包
這裡我建的是maven工程,pom座標配置如下
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.0</version>
</dependency>
程式碼
package com.taotao.rest.jedis; import java.util.HashSet; import javax.swing.Spring; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.taotao.rest.dao.JedisClient; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisCluster; import redis.clients.jedis.JedisPool; public class JedisTest { //單例項連結測試 @Test public void testJedisSingel() { //建立jedis物件 Jedis jedis=new Jedis("192.168.154.128",6379); //呼叫jedis物件方法,方法名和Jedis命令一致 jedis.set("key1", "jedis test"); String string=jedis.get("key1"); System.out.println(string); } //使用連線池連線測試 @Test public void testJedisPool() { //建立Jedis連結池 JedisPool pool=new JedisPool("192.168.154.128",6379); //從連線池中獲得Jedis物件 Jedis jedis=pool.getResource(); String string=jedis.get("key1"); System.out.println(string); jedis.close(); pool.close(); } //叢集版連結測試 @Test public void testJedisCluster() { HashSet<HostAndPort> nodes=new HashSet<>(); nodes.add(new HostAndPort("192.168.154.128",6379)); nodes.add(new HostAndPort("192.168.154.128",6380)); nodes.add(new HostAndPort("192.168.154.128",6381)); nodes.add(new HostAndPort("192.168.154.128",6382)); nodes.add(new HostAndPort("192.168.154.128",6383)); nodes.add(new HostAndPort("192.168.154.128",6384)); JedisCluster cluster=new JedisCluster(nodes); cluster.set("key1", "test"); String string=cluster.get("key1"); System.out.println(string); cluster.close(); } //spring整合單機版測試 @Test public void testSpringJedisSingle(){ ApplicationContext applicationContext=new ClassPathXmlApplicationContext("classpath:/spring/applicationContext-*.xml"); JedisPool pool=(JedisPool) applicationContext.getBean("redisClient"); Jedis jedis=pool.getResource(); String string=jedis.get("key1"); System.out.println(string); jedis.close(); pool.close(); } //spring整合叢集版測試 @Test public void testSpringJedisCluster() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-*.xml"); JedisCluster jedisCluster = (JedisCluster) applicationContext.getBean("redisClient"); String string = jedisCluster.get("key1"); System.out.println(string); jedisCluster.close(); } }