Redis使用初步
学习的时候先在Windows进行
下载:https://github.com/MicrosoftArchive/redis/releases
按照默认安装,
启动redis服务器命令
cd 到redis安装目录,redis-server redis.windows.conf
作为服务安装 redis-server --service -install redis.windows.conf
使用redis客户端存储和读取键值对
redis-cli.exe -h 127.0.0.1 -p 6379
set hi " good to know you"
get hi
系统就返回“good to know you”字符串
Java 中使用Redis
把Jedis的maven配置
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
写到maven工程的pom.xml文件中。
示例:
Jedis测试代码
import redis.clients.jedis.Jedis; public class MainFIle { public static void main(String[] args) { // TODO Auto-generated method stub Jedis jd=new Jedis("127.0.0.1"); System.out.println("当前Redis服务状态"+jd.ping()); jd.set("hi", "nice to meet you"); System.out.println("value of hi is "+jd.get("hi"));
jd.close(); } }
使用连接池
/** * 使用连接池 */ @Test public void testJedisPool() { //创建jedis连接池 JedisPool pool = new JedisPool("192.168.25.153", 6379); //从连接池中获得Jedis对象 Jedis jedis = pool.getResource(); String string = jedis.get("key1"); System.out.println(string); //关闭jedis对象 jedis.close(); pool.close(); }
集群测试
@Test public void testJedisCluster() { HashSet<HostAndPort> nodes = new HashSet<>(); nodes.add(new HostAndPort("192.168.25.153", 7001)); nodes.add(new HostAndPort("192.168.25.153", 7002)); nodes.add(new HostAndPort("192.168.25.153", 7003)); nodes.add(new HostAndPort("192.168.25.153", 7004)); nodes.add(new HostAndPort("192.168.25.153", 7005)); nodes.add(new HostAndPort("192.168.25.153", 7006)); JedisCluster cluster = new JedisCluster(nodes); cluster.set("key1", "1000"); String string = cluster.get("key1"); System.out.println(string); cluster.close(); }
参考文章:
https://www.cnblogs.com/loveincode/p/7508781.html#autoid-6-2-2
https://www.cnblogs.com/anxiao/p/8378218.html