Java使用Redis
Redis在Java Web应用中有两个主要场景:
- 缓存常用的数据
- 需要高速读/写的场合进行快速读/写,例如商品抢购和抢红包的场合。
1. 下载Redis依赖包jedis.jar
,Add it to the build path.
http://www.java2s.com/Code/JarDownload/jedis/jedis.jar.zip
2. 测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| import redis.clients.jedis.Jedis;
public class ServiceTest { public static void main(String[] args) { Jedis jedis = new Jedis("localhost"); System.out.println("服务正在运行: "+jedis.ping()); jedis.set("name", "Danny"); System.out.println("redis 存储的字符串为: "+ jedis.get("name"));
jedis.lpush("subject-list", "math"); jedis.lpush("subject-list", "chemistry"); jedis.lpush("subject-list", "geography"); List<String> list = jedis.lrange("subject-list", 0 ,2); for(int i=0; i<list.size(); i++) { System.out.println("列表项为: "+list.get(i)); } } }
|
The output:
1 2 3 4 5
| The service is running: PONG The String is: Danny The item is: geography The item is: chemistry The item is: math
|