Redis入门(四)-Java操作Redis

《Redis入门》系列文章的第四篇,这一节看一下如何用Java版本的redis客户端工具--Jedis来操作redis。

Jedis封装了丰富的api来对redis的五种数据类型 string 、hash 、list 、set 、zset进行操作,可以说命令行界面的命令它都有。

开始在 Java 中使用 Redis 前, 我们需要确保已经安装了 redis 服务,且你的机器上能正常使用 Java。

导入Java操作Redis的客户端工具--Jedis

1<dependency>
2     <groupId>redis.clients</groupId>
3     <artifactId>jedis</artifactId>
4     <version>3.1.0</version>
5</dependency>

Jedis操作Redis

操作string

 1//string
2//连接本地Redis服务
3Jedis jedis = new Jedis("127.0.0.1",6379);
4
5jedis.set("name","walking");
6jedis.set("weixin","编程大道");
7
8System.out.println(jedis.get("name"));//walking
9System.out.println(jedis.get("weixin"));//编程大道
10jedis.close();

操作list

 1//list
2Jedis jedis = new Jedis("127.0.0.1",6379);
3
4jedis.del("cityList");
5jedis.lpush("cityList","北京","上海","重庆","深圳");
6
7List<String> cityList1 = jedis.lrange("cityList", 0, -1);
8System.out.println(cityList1);//[深圳, 重庆, 上海, 北京]
9System.out.println(jedis.llen("cityList"));//4
10System.out.println(jedis.lpop("cityList"));//深圳
11System.out.println(jedis.rpop("cityList"));//北京
12System.out.println(jedis.llen("cityList"));//2
13
14jedis.close();

操作hash

 1//hash
2Jedis jedis = new Jedis("127.0.0.1",6379);
3
4jedis.hset("user_0001","name","walking");
5jedis.hset("user_0001","sex","1");
6jedis.hset("user_0001","age","24");
7
8System.out.println(jedis.hget("user_0001", "name"));
9System.out.println(jedis.hget("user_0001", "sex"));
10System.out.println(jedis.hget("user_0001", "age"));
11Map<String, String> user_0001 = jedis.hgetAll("user_0001");
12System.out.println(user_0001);//{name=walking, age=24, sex=1}
13jedis.hdel("user_0001","age");
14user_0001 = jedis.hgetAll("user_0001");
15System.out.println(user_0001);//{name=walking, sex=1}
16
17jedis.close();

操作set

 1//set
2Jedis jedis = new Jedis("127.0.0.1",6379);
3
4jedis.sadd("articleSet","0001","0002","0003","0004");
5//返回key集合所有的元素 
6System.out.println(jedis.smembers("articleSet"));// [0004, 0001, 0002, 0003]
7//移除并返回一个随机元素
8System.out.println(jedis.spop("articleSet"));//0001
9System.out.println(jedis.smembers("articleSet"));//[0004, 0002, 0003]
10System.out.println(jedis.srandmember("articleSet"));//随机返回 0003
11jedis.sadd("articleSet2","0022", "0004", "0021");
12System.out.println(jedis.sinter("articleSet","articleSet2"));//交集 [0004]
13
14jedis.close();

操作zset

 1//zset
2Jedis jedis = new Jedis("127.0.0.1",6379);
3
4jedis.zadd("zset",3D,"0003");
5jedis.zadd("zset",1D,"0001");
6jedis.zadd("zset",4D,"0004");
7jedis.zadd("zset",2.5D,"00025");
8jedis.zadd("zset",2D,"0002");
9
10System.out.println(jedis.zcard("zset"));//5
11System.out.println(jedis.zcount("zset",2,3));//3
12//通过分值区间查找成员
13Set<String> zset = jedis.zrangeByScore("zset", 2D, 3D);
14System.out.println(zset);////[0002, 00025, 0003]
15//通过下标查找成员
16System.out.println(jedis.zrange("zset", 0, -1));//[0001, 0002, 00025, 0003, 0004]
17ScanResult<Tuple> zset1 = jedis.zscan("zset", ScanParams.SCAN_POINTER_START);
18System.out.println(zset1.getCursor());//0
19System.out.println(zset1.getResult());//[[0001,1.0], [0002,2.0], [00025,2.5], [0003,3.0], [0004,4.0]]
20jedis.close();

系统命令

1//server
2System.out.println("=========== server =============");
3System.out.println(jedis.dbSize());//key的数量
4System.out.println(jedis.time());//系统时间
5System.out.println(jedis.clientList());//客户端连接列表
6System.out.println(jedis.info());//redis信息

output

  1=========== server =============
2//key的数量
37
4//系统时间
5[1575610535, 74018]
6//客户端连接列表
7id=42 addr=127.0.0.1:63466 fd=7 name= age=0 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=32768 obl=0 oll=0 omem=0 events=r cmd=client
8//redis信息
9# Server
10redis_version:3.2.100
11redis_git_sha1:00000000
12redis_git_dirty:0
13redis_build_id:dd26f1f93c5130ee
14redis_mode:standalone
15os:Windows  
16arch_bits:64
17multiplexing_api:WinSock_IOCP
18process_id:10960
19run_id:1acb04abaca68c04e9e027017c301c04f9a402d2
20tcp_port:6379
21uptime_in_seconds:15572
22uptime_in_days:0
23hz:10
24lru_clock:15329446
25executable:D:\mysoft\redis-3.2.100\redis-server.exe
26config_file:D:\mysoft\redis-3.2.100\redis.windows.conf
27
28# Clients
29connected_clients:1
30client_longest_output_list:0
31client_biggest_input_buf:0
32blocked_clients:0
33
34# Memory
35used_memory:690720
36used_memory_human:674.53K
37used_memory_rss:689688
38used_memory_rss_human:673.52K
39used_memory_peak:690720
40used_memory_peak_human:674.53K
41total_system_memory:0
42total_system_memory_human:0B
43used_memory_lua:37888
44used_memory_lua_human:37.00K
45maxmemory:0
46maxmemory_human:0B
47maxmemory_policy:noeviction
48mem_fragmentation_ratio:1.00
49mem_allocator:jemalloc-3.6.0
50
51# Persistence
52loading:0
53rdb_changes_since_last_save:15
54rdb_bgsave_in_progress:1
55rdb_last_save_time:1575603910
56rdb_last_bgsave_status:ok
57rdb_last_bgsave_time_sec:0
58rdb_current_bgsave_time_sec:0
59aof_enabled:0
60aof_rewrite_in_progress:0
61aof_rewrite_scheduled:0
62aof_last_rewrite_time_sec:-1
63aof_current_rewrite_time_sec:-1
64aof_last_bgrewrite_status:ok
65aof_last_write_status:ok
66
67# Stats
68total_connections_received:41
69total_commands_processed:894
70instantaneous_ops_per_sec:19
71total_net_input_bytes:34647
72total_net_output_bytes:18067
73instantaneous_input_kbps:0.76
74instantaneous_output_kbps:0.25
75rejected_connections:0
76sync_full:0
77sync_partial_ok:0
78sync_partial_err:0
79expired_keys:0
80evicted_keys:0
81keyspace_hits:453
82keyspace_misses:7
83pubsub_channels:0
84pubsub_patterns:0
85latest_fork_usec:55286
86migrate_cached_sockets:0
87
88# Replication
89role:master
90connected_slaves:0
91master_repl_offset:0
92repl_backlog_active:0
93repl_backlog_size:1048576
94repl_backlog_first_byte_offset:0
95repl_backlog_histlen:0
96
97# CPU
98used_cpu_sys:0.53
99used_cpu_user:0.27
100used_cpu_sys_children:0.00
101used_cpu_user_children:0.00
102
103# Cluster
104cluster_enabled:0
105
106# Keyspace
107db0:keys=7,expires=0,avg_ttl=0

池化技术

和关系型数据库一样,Jedis也封装了池化技术来管理redis连接。

 1//连接池配置
2JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
3
4//连接耗尽时是否阻塞, false报异常,true阻塞直到超时, 默认true
5jedisPoolConfig.setBlockWhenExhausted(true);
6jedisPoolConfig.setMaxTotal(200);//最大连接数, 默认8个
7jedisPoolConfig.setMaxIdle(20);//最大空闲连接数, 默认8个
8jedisPoolConfig.setMinIdle(20);//最小空闲连接数, 默认0
9//连接耗尽时是否阻塞, false报异常,true阻塞直到超时, 默认true
10jedisPoolConfig.setBlockWhenExhausted(true);
11//获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间,  默认-1
12jedisPoolConfig.setMaxWaitMillis(5000);
13//在获取连接的时候检查有效性, 默认false
14jedisPoolConfig.setTestOnBorrow(true);
15//在空闲时检查有效性, 默认false
16jedisPoolConfig.setTestWhileIdle(false);
17//逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
18jedisPoolConfig.setTimeBetweenEvictionRunsMillis(300000);
19//逐出连接的最小空闲时间 默认1800000毫秒(30分钟)
20jedisPoolConfig.setMinEvictableIdleTimeMillis(300000);
21//每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3
22jedisPoolConfig.setNumTestsPerEvictionRun(50);
23
24String ip = "127.0.0.1";
25int port = 6379;
26//实例化连接池
27JedisPool jedisPool = new JedisPool(jedisPoolConfig,ip,port);
28
29//获得连接
30Jedis client = jedisPool.getResource();
31client.set("name","walking");
32System.out.println(client.get("name"));
33
34//释放连接
35client.close();

更多命令请参考:
Redis命令中心
Redis API

系列教程
Redis入门(一)-Redis简介
Redis入门(二)-Redis能够做什么
Redis入门(三)-Redis的安装及操作key的命令介绍

上一篇:io模型---非阻塞模型


下一篇:java操作redis集群配置[可配置密码]和工具类(比较好用)