1.Java集成Jedis
开始在 Java 中使用 Redis 前, 我们需要确保已经安装并启动 redis 服务及 Java redis 驱动,且你的机器上能正常使用 Java。可以取Maven仓库下载驱动包 下载 jedis.jar,。
1.1.搭建工程
- 搭建普通java项目,项目名:jedis-demo
1.2.导入Jedis依赖
- 把Jedis和连接池包一起导入进来
commons-pool2-2.2.jar #连接池 jedis-2.5.2.jar #Jedis核心包 • 1 • 2
1.3.编写测试类
- 通过Jedis客户端对象连接Redis,调用API进行Redis
@Test public void testJedis()throws Exception{ //创建连接 String host ="127.0.0.1"; //端口 int port = 6379; //超时时间,1秒超时 int timeout = 1000; //jedis客户端 Jedis jedis = new Jedis(host,port,timeout); //认证 jedis.auth("123456"); //执行操作,保存值 jedis.set("username","wang da cui"); //获取值 String result = jedis.get("username"); System.out.print(result); //关闭连接 jedis.close(); }
1.4.连接池的使用
如果直接使用 Jedis
链接Redis会造成频繁的Jedis对象创建和销毁,对性能会有很大的影响,所以我们会选择使用连接池来链接性能。原理同Mysql连接池
- 编写测试方法,使用
JedisPool
连接池对象
@Test public void test()throws Exception{ //1 创建jedispool配置对象 JedisPoolConfig config = new JedisPoolConfig(); //2 做配置 //最大空闲连接数 config.setMaxIdle(2); //最大链接对象数 config.setMaxTotal(10); //链接超时时间 config.setMaxWaitMillis(1*1000); //获取连接是测试连接是否畅通 config.setTestOnBorrow(true); //3 创建jedispool连接池对戏 //参数:配置对象,redis主机地址 ,超时时间,密码 JedisPool pool = new JedisPool(config,"127.0.0.1",6379,1*1000,"123456"); //4 通过jedispool获取连接 Jedis jedis = pool.getResource(); //5 执行操作 jedis.set("age",10); String result = jedis.get("age"); System.out.println(result); // 6 释放连接 , 底层做了兼容,如果是连接池操作就是释放,如果是连接操作就是关闭 jedis.close(); // 7 摧毁连接池-如果是真正项目中它应该是一个受spring管理的单例 pool.destroy(); }
- 工具类封装:JedisPool应该是单例的(想想你的Mybatis的DataSource也只是创建了一个),为了方便使用,将
JedisPool
封装成工具。
redis.properties
redis.host=127.0.0.1 redis.port=6379 redis.password=123456 redis.timeout=5000 • 1 • 2 • 3 • 4
RedisUtils
package org.example; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; /** * 获取连接池对象 */ public enum RedisUtils { INSTANCE; //连接池 static JedisPool jedisPool = null; static { //1 创建连接池配置对象 JedisPoolConfig config = new JedisPoolConfig(); //2 进行配置-四个配置 config.setMaxIdle(1);//最小连接数 config.setMaxTotal(11);//最大连接数 config.setMaxWaitMillis(10 * 1000L);//最长等待时间 config.setTestOnBorrow(true);//测试连接时是否畅通 //3 通过配置对象创建连接池对象 Properties properties = null; try { properties = new Properties(); properties.load(RedisUtils.class.getClassLoader().getResourceAsStream("redis.properties")); } catch (IOException e) { e.printStackTrace(); } String host = properties.getProperty("redis.host"); String port = properties.getProperty("redis.port"); String password = properties.getProperty("redis.password"); String timeout = properties.getProperty("redis.timeout"); jedisPool = new JedisPool(config, host, Integer.valueOf(port),Integer.valueOf(timeout), password); } //获取连接 public Jedis getSource() { return jedisPool.getResource(); } //关闭资源 public void closeSource(Jedis jedis) { if (jedis != null) { jedis.close(); } } /** * hash操作字符串============================================== */ public List<String> hvals(String key) { Jedis jedis = getSource(); List<String> hvals = jedis.hvals(key); closeSource(jedis); return hvals; } public Set<String> hkeys(String key) { Jedis jedis = getSource(); Set<String> hkeys = jedis.hkeys(key); closeSource(jedis); return hkeys; } public Long hset(String key,String field,String value) { Jedis jedis = getSource(); Long result = jedis.hset(key,field,value); closeSource(jedis); return result; } public String hmset(String key, Map<String,String> data) { Jedis jedis = getSource(); String result = jedis.hmset(key,data); closeSource(jedis); return result; } public String hget(String key,String field) { Jedis jedis = getSource(); String value = jedis.hget(key, field); closeSource(jedis); return value; } /** * hash操作byte[]============================================== */ public List<byte[]> hvals(byte[] key) { Jedis jedis = getSource(); List<byte[]> hvals = jedis.hvals(key); closeSource(jedis); return hvals; } public Set<byte[]> hkeys(byte[] key) { Jedis jedis = getSource(); Set<byte[]> hkeys = jedis.hkeys(key); closeSource(jedis); return hkeys; } public Long hset(byte[] key,byte[] field,byte[] value) { Jedis jedis = getSource(); Long result = jedis.hset(key,field,value); closeSource(jedis); return result; } public String hmset(byte[] key, Map<byte[],byte[]> data) { Jedis jedis = getSource(); String result = jedis.hmset(key,data); closeSource(jedis); return result; } public byte[] hget(byte[] key,byte[] field) { Jedis jedis = getSource(); byte[] value = jedis.hget(key, field); closeSource(jedis); return value; } /** * 删除key */ public boolean del(String key) { Jedis jedis = getSource(); long result = jedis.del(key); closeSource(jedis); return result > 0; } /** * 设置字符值 * * @param key * @param value :value是字符串,如果要存储对象,转成JSON字符串在存储 */ public void set(String key, String value) { Jedis jedis = getSource(); jedis.set(key, value); closeSource(jedis); } /** * 设置 * @param key * @param value */ public void set(byte[] key, byte[] value) { Jedis jedis = getSource(); jedis.set(key, value); closeSource(jedis); } /** * * @param key * @return */ public byte[] get(byte[] key) { Jedis jedis = getSource(); try { return jedis.get(key); } catch (Exception e) { e.printStackTrace(); } finally { closeSource(jedis); } return null; } /** * 设置字符值 * * @param key * @return :返回的是JSON格式的字符串 ,考虑转对象 */ public String get(String key) { Jedis jedis = getSource(); try { return jedis.get(key); } catch (Exception e) { e.printStackTrace(); } finally { closeSource(jedis); } return null; } }
2.Jedis的API操作
使用jedis来操作redis的key和value,而value有很多种类型,和命令操作一样。
2.1.key的操作
System.out.println(jedis.keys("*"));
2.2.String的操作
System.out.println(jedis.set("name","zhangsan"));//新增 System.out.println(jedis.get("name"));//获取 System.out.println(jedis.set("name","zhangsan1"));//修改 System.out.println(jedis.get("name"));//获取 System.out.println(jedis.del("name"));//删除 System.out.println(jedis.keys("*"));//查看所有的key
2.3.List的操作
jedis.lpush("students1","1","2","3","5","6"); //添加数据 System.out.println(jedis.lrange("students1", 0, 3)); //获取数据
- 排序操作,对于数字元素排序不需要加
SortingParams
,对于字符串需要指定SortingParams
,并且指定使用assii值排序
//对数字排序 jedis.flushDB(); //添加数据 jedis.lpush("nums","1","2","3","4","8","5","3","1"); //排序 System.out.println(jedis.sort("nums")); //指定排序方式 SortingParams sortingParams1 = new SortingParams(); sortingParams1.desc(); System.out.println(jedis.sort("nums", sortingParams1)); //对字母排序 jedis.lpush("langues","java","php","c++","test","ui"); SortingParams sortingParams = new SortingParams(); sortingParams.alpha(); sortingParams.desc(); System.out.println(jedis.sort("langues",sortingParams));
2.4.Set的操作
jedis.sadd("students2","a1","b1","c1","b1"); //添加数据 System.out.println(jedis.smembers("students2")); //获取成员
2.5.Hash操作
jedis.hset("students3","student","zhangsan"); //添加数据 System.out.println(jedis.hget("students3", "student")); //获取数据
2.6.Hash存储对象
序列化SerializeUtil.java
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class SerializeUtil { /** * 序列化 * * @param object * @return */ public static byte[] serialize(Object object) { ObjectOutputStream oos = null; ByteArrayOutputStream baos = null; try { // 序列化 baos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(baos); oos.writeObject(object); byte[] bytes = baos.toByteArray(); return bytes; } catch (Exception e) { } return null; } /** * 反序列化 * * @param bytes * @return */ public static Object unserialize(byte[] bytes) { ByteArrayInputStream bais = null; try { // 反序列化 bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); return ois.readObject(); } catch (Exception e) { } return null; } }
实体类User.java
import java.io.Serializable; public class User implements Serializable { @Override public String toString() { return "User{" + "username='" + username + '\'' + ", id=" + id + '}'; } private String username; private Long id; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public User() { } public User(String username, Long id) { this.username = username; this.id = id; } }
测试代码
import com.alibaba.fastjson.JSON; import org.junit.Test; import java.util.*; public class RedisTest { private User createUser(){ return new User("zs",1L); } private List<User> createUsers(){ return Arrays.asList( new User("zs",1L), new User("zs",2L), new User("zs",3L), new User("zs",4L), new User("zs",5L), new User("zs",6L)); } //查询所有的用户 //根据id查询某个用户 @Test public void test(){ //存放==================================================================== List<User> users = createUsers(); Map<String,String> data = new HashMap<>(users.size()); users.forEach(user -> { data.put(user.getId().toString(),JSON.toJSONString(user)); }); String hmsetResult = RedisUtils.INSTANCE.hmset("users", data); System.out.println(hmsetResult); RedisUtils.INSTANCE.hset("users","7",JSON.toJSONString(new User("zs",7L))); //取所有值================================================================== List<String> values = RedisUtils.INSTANCE.hvals("users"); List<User> result = new ArrayList<>(values.size()); values.forEach(value ->{ result.add(JSON.parseObject(value,User.class)); }); System.out.println(values); //根据ID取User============================================================== String user = RedisUtils.INSTANCE.hget("users","1"); System.out.println(user); } //查询所有的用户 //根据id查询某个用户 @Test public void test2(){ //存放==================================================================== List<User> users = createUsers(); Map<byte[],byte[]> data = new HashMap<>(users.size()); users.forEach(user -> { data.put(user.getId().toString().getBytes(),SerializeUtil.serialize(user)); }); String hmsetResult = RedisUtils.INSTANCE.hmset("users".getBytes(), data); System.out.println(hmsetResult); RedisUtils.INSTANCE.hset("users".getBytes(),"7".getBytes(),SerializeUtil.serialize(new User("zs",7L))); //取所有值================================================================== List<byte[]> values = RedisUtils.INSTANCE.hvals("users".getBytes()); List<User> result = new ArrayList<>(values.size()); values.forEach(value ->{ result.add(((User)SerializeUtil.unserialize(value))); }); System.out.println(result); //根据ID取User============================================================== byte[] user = RedisUtils.INSTANCE.hget("users".getBytes(),"7".getBytes()); System.out.println(SerializeUtil.unserialize(user)); } //查询所有的用户 //根据id查询某个用户 @Test public void test3(){ //存放==================================================================== RedisUtils.INSTANCE.hset("users".getBytes(),"7".getBytes(),SerializeUtil.serialize(new User("zs",7L))); //根据ID取User============================================================== byte[] user = RedisUtils.INSTANCE.hget("users".getBytes(),"7".getBytes()); System.out.println(SerializeUtil.unserialize(user)); } }
2.7.事务操作
jedis.set("name","zs"); jedis.set("age",18); //开启事务 Transaction multi = jedis.multi(); multi.incr("name"); multi.incr("age"); //提交事务 List<Object> result = multi.exec(); System.out.println(result); //关闭连接 jedis.close(); //关闭连接池 pool.destory();