分享

java连接redis存取数据(详细)

 三十的狼 2020-12-17

声明:本文章仅供参考,学无止境,若有不足之处请指出,非常感谢!

源代码+相关工具下载:https://download.csdn.net/download/corleone_4ever/10811258

目录

一.相关工具

二.准备工作

三.新建jedis项目

四.编写代码

五.连接测试

六.注意事项


一.相关工具

 

如果没有服务器的同学,可以在自己的电脑安装虚拟机,我这里使用的是:VMware10+centos7+redis5.0

贴出 VMware10+centos7 下载地址:https://download.csdn.net/download/corleone_4ever/10812834

 

开发工具用的myeclipse2014

jdk版本为1.7

 

 

java连接redis所需依赖jar包:

jedis-2.9.0.jar (redis连接工具)

commons-pool2-2.6.0.jar (jedis连接池)

fastjson-1.2.2.jar (阿里的json序列化工具)

junit-4.12.jar (单元测试)

贴出demo下载地址(包含vm10+centos7+redis5.0+jedis连接依赖jar包及其相关工具文档):

https://download.csdn.net/download/corleone_4ever/10811258

二.准备工作

在通过java连接redis之前,首先得配置好java环境

安装好redis,并且能通过外部访问(需要关闭对应防火墙)

1.启动redis 

2.输入ifconfig获取本机ip,通过外部连接测试,我这里使用的是RedisDesktopManager

 3.新建连接,输入你自己的ip,redis端口和密码,没有密码就不输入

 4.连接成功


 

 

三.新建jedis项目

1.新建项目:右键→new→other→选择web下的Dynamic Web Project

2.这里项目名称为jedis

 

3.引入相关jar包,直接把依赖jar包复制到WEB-INF下的lib目录下

4.引入 junit:右键项目→properties-→ava build parh→Libraries→ADD Library→Junit→Finish

这里也可以直接引用junit包,我是用的myeclipse自带的

 5.新建包com.redis.test   项目结构如下

 四.编写代码

这里直接贴出代码

1.redis.properties : redis连接配置文件

连接池配置参考:https://blog.csdn.net/wx5040257/article/details/78474157

  1. #redis服务器ip
  2. redis.ip=192.168.10.21
  3. #redis服务器端口号
  4. redis.port=6379
  5. #redis密码
  6. redis.passWord=
  7. #与服务器建立连接的超时时间
  8. redis.timeout=3000
  9. #jedis的最大活跃连接数
  10. pool.maxTotal=10
  11. #jedis最大空闲连接数
  12. pool.maxIdle=3
  13. #jedis池没有连接对象返回时,等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。
  14. #如果超过等待时间,则直接抛出JedisConnectionException
  15. pool.maxWaitMillis=3000

2.RedisPoolUtil : 连接池配置工具

这里使用单例模式+双重锁定写的一个redis连接池配置工具(如需xml配置连接池,自行百度,原理相同)

  1. package com.redis.test;
  2. import java.util.Properties;
  3. import redis.clients.jedis.Jedis;
  4. import redis.clients.jedis.JedisPool;
  5. import redis.clients.jedis.JedisPoolConfig;
  6. import redis.clients.jedis.exceptions.JedisConnectionException;
  7. /**
  8. * jedis连接池工具
  9. * @author corleone
  10. * @date 2018年11月27日
  11. */
  12. public class RedisPoolUtil {
  13. private volatile static JedisPool jedisPool = null;
  14. private static String redisConfigFile = "redis.properties";
  15. //把redis连接对象放到本地线程中
  16. private static ThreadLocal<Jedis> local=new ThreadLocal<Jedis>();
  17. private RedisPoolUtil() {
  18. }
  19. /**
  20. * 初始化连接池
  21. * @author corleone
  22. * @date 2018年11月27日
  23. */
  24. public static void initialPool() {
  25. try {
  26. Properties props = new Properties();
  27. //加载连接池配置文件
  28. props.load(RedisPoolUtil.class.getClassLoader().getResourceAsStream(redisConfigFile));
  29. // 创建jedis池配置实例
  30. JedisPoolConfig config = new JedisPoolConfig();
  31. // 设置池配置项值
  32. config.setMaxTotal(Integer.valueOf(props.getProperty("pool.maxTotal")));
  33. config.setMaxIdle(Integer.valueOf(props.getProperty("pool.maxIdle")));
  34. config.setMaxWaitMillis(Long.valueOf(props.getProperty("pool.maxWaitMillis")));
  35. // 根据配置实例化jedis池
  36. jedisPool = new JedisPool(config, props.getProperty("redis.ip"),
  37. Integer.valueOf(props.getProperty("redis.port")),
  38. Integer.valueOf(props.getProperty("redis.timeout")),
  39. "".equals(props.getProperty("redis.passWord"))?null:props.getProperty("redis.passWord"));
  40. System.out.println("连接池初始化成功");
  41. } catch (Exception e) {
  42. e.printStackTrace();
  43. System.err.println("连接池初始化失败");
  44. }
  45. }
  46. /**
  47. * 获取连接
  48. * @return
  49. * @author corleone
  50. * @date 2018年11月27日
  51. */
  52. public static Jedis getInstance() {
  53. //Redis对象
  54. Jedis jedis =local.get();
  55. if(jedis==null){
  56. if (jedisPool == null) {
  57. synchronized (RedisPoolUtil.class) {
  58. if (jedisPool == null) {
  59. initialPool();
  60. }
  61. }
  62. }
  63. try{
  64. jedis = jedisPool.getResource();
  65. }catch(JedisConnectionException e){
  66. e.printStackTrace();
  67. }
  68. local.set(jedis);
  69. }
  70. return jedis;
  71. }
  72. /**
  73. * 关闭连接
  74. * @author corleone
  75. * @date 2018年11月27日
  76. */
  77. public static void closeConn(){
  78. Jedis jedis =local.get();
  79. if(jedis!=null){
  80. jedis.close();
  81. }
  82. local.set(null);
  83. }
  84. }

3.SerializeUtil : java序列化/反序列化封装工具

  1. package com.redis.test;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.ObjectInputStream;
  5. import java.io.ObjectOutputStream;
  6. /**
  7. * java序列化/反序列化工具
  8. * @author corleone
  9. * @date 2018年11月27日
  10. */
  11. public class SerializeUtil {
  12. /**
  13. * 序列化
  14. * @param object
  15. * @author corleone
  16. * @date 2018年11月27日
  17. */
  18. public static byte[] serizlize(Object object){
  19. ObjectOutputStream oos = null;
  20. ByteArrayOutputStream baos = null;
  21. try {
  22. baos = new ByteArrayOutputStream();
  23. oos = new ObjectOutputStream(baos);
  24. oos.writeObject(object);
  25. byte[] bytes = baos.toByteArray();
  26. return bytes;
  27. } catch (Exception e) {
  28. e.printStackTrace();
  29. }finally {
  30. try {
  31. if(baos != null){
  32. baos.close();
  33. }
  34. if (oos != null) {
  35. oos.close();
  36. }
  37. } catch (Exception e2) {
  38. e2.printStackTrace();
  39. }
  40. }
  41. return null;
  42. }
  43. /**
  44. * 反序列化
  45. * @param bytes
  46. * @author corleone
  47. * @date 2018年11月27日
  48. */
  49. public static Object deserialize(byte[] bytes){
  50. ByteArrayInputStream bais = null;
  51. ObjectInputStream ois = null;
  52. try{
  53. bais = new ByteArrayInputStream(bytes);
  54. ois = new ObjectInputStream(bais);
  55. return ois.readObject();
  56. }catch(Exception e){
  57. e.printStackTrace();
  58. }finally {
  59. try {
  60. } catch (Exception e2) {
  61. e2.printStackTrace();
  62. }
  63. }
  64. return null;
  65. }
  66. }

4.MapUtil : 对象与map相互转换封装工具

能够转换的对象需要该对象的属性必须是String或int类型,我这里只做演示,其他类型需要自己扩展

  1. package com.redis.test;
  2. import java.lang.reflect.Field;
  3. import java.lang.reflect.Method;
  4. import java.lang.reflect.Modifier;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. /**
  8. * java反射机制
  9. * 对象与map相互转换
  10. * @author corleone
  11. * @date 2018年11月14日
  12. */
  13. public class MapUtil {
  14. /**
  15. * map转对象(目前只支持对象中含有String和int类型的属性,其他类型需要自己扩展)
  16. * @param map
  17. * @param beanClass
  18. * @throws Exception
  19. * @author corleone
  20. * @date 2018年11月27日
  21. */
  22. public static <T> Object mapToObject(Map<String, String> map, Class<?> beanClass)
  23. throws Exception {
  24. if (map == null)
  25. return null;
  26. Object obj = beanClass.newInstance();
  27. Field[] fields = obj.getClass().getDeclaredFields();
  28. for (Field field : fields) {
  29. int mod = field.getModifiers();
  30. if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
  31. continue;
  32. }
  33. field.setAccessible(true);
  34. if(field.getType().equals(int.class)){
  35. field.set(obj, Integer.parseInt(map.get(field.getName())));
  36. }else{
  37. field.set(obj, (Object)map.get(field.getName()));
  38. }
  39. }
  40. return obj;
  41. }
  42. /**
  43. * 对象转map(目前只支持对象属性为基本类型)
  44. * @param obj
  45. * @throws Exception
  46. * @author corleone
  47. * @date 2018年11月27日
  48. */
  49. public static Map<String, String> objectToMap(Object obj) throws Exception {
  50. if (obj == null) {
  51. return null;
  52. }
  53. Map<String, String> map = new HashMap<String, String>();
  54. Field[] declaredFields = obj.getClass().getDeclaredFields();
  55. for (Field field : declaredFields) {
  56. field.setAccessible(true);
  57. map.put(field.getName(), field.get(obj).toString());
  58. }
  59. return map;
  60. }
  61. }

 

5.ReflectUtil : 通过反射根据对象属性名称获取对应属性的值(在实际项目中用aop实现连接redis的时候有用到,本次演示没有用到该工具类,所以不贴出代码,有兴趣可以下载demo自己研究下:一.相关工具)

6.RedisOps : jedis存取常用数据封装工具类

这里写了String类型和hash类型两种数据存取,如需要存取其他数据类型可以自己扩展

  1. package com.redis.test;
  2. import com.alibaba.fastjson.JSON;
  3. import redis.clients.jedis.Jedis;
  4. /**
  5. * redis存取工具类
  6. * @author corleone
  7. * @date 2018年11月15日
  8. */
  9. public class RedisOps {
  10. /**
  11. * kv字符串存
  12. * @param key
  13. * @param value
  14. * @author corleone
  15. * @date 2018年11月15日
  16. */
  17. public static void set(String key,String value){
  18. Jedis jedis = RedisPoolUtil.getInstance();
  19. jedis.set(key, value);
  20. RedisPoolUtil.closeConn();
  21. }
  22. /**
  23. * kv字符串取
  24. * @param key
  25. * @return 字符串
  26. * @author corleone
  27. * @date 2018年11月15日
  28. */
  29. public static String get(String key){
  30. Jedis jedis = RedisPoolUtil.getInstance();
  31. String value = jedis.get(key);
  32. RedisPoolUtil.closeConn();
  33. return value;
  34. }
  35. /**
  36. * kv对象存(java序列化方式)
  37. * @param key
  38. * @param object 对象类必须实现序列化
  39. * @author corleone
  40. * @date 2018年11月15日
  41. */
  42. public static void setObjectSerialize(String key,Object object){
  43. Jedis jedis = RedisPoolUtil.getInstance();
  44. if(jedis==null){
  45. return;
  46. }
  47. jedis.set(key.getBytes(), SerializeUtil.serizlize(object));
  48. RedisPoolUtil.closeConn();
  49. }
  50. /**
  51. * kv对象取(java反序列化)
  52. * @param key
  53. * @return 对象
  54. * @author corleone
  55. * @date 2018年11月15日
  56. */
  57. public static Object getObjectSerialize(String key){
  58. Jedis jedis = RedisPoolUtil.getInstance();
  59. if(jedis==null){
  60. return null;
  61. }
  62. byte[] bytes = jedis.get(key.getBytes());
  63. RedisPoolUtil.closeConn();
  64. if(bytes==null){
  65. return null;
  66. }
  67. return SerializeUtil.deserialize(bytes);
  68. }
  69. /**
  70. * 删除key
  71. * @param key
  72. * @author corleone
  73. * @date 2018年11月15日
  74. */
  75. public static void del(String key){
  76. Jedis jedis = RedisPoolUtil.getInstance();
  77. if(jedis==null){
  78. return;
  79. }
  80. jedis.del(key.getBytes());
  81. RedisPoolUtil.closeConn();
  82. }
  83. /**
  84. * kv对象存(json方式)
  85. * @param key
  86. * @param object
  87. * @author corleone
  88. * @date 2018年11月15日
  89. */
  90. public static void setObjectJson(String key,Object object){
  91. Jedis jedis = RedisPoolUtil.getInstance();
  92. if(jedis==null){
  93. return;
  94. }
  95. jedis.set(key, JSON.toJSONString(object));
  96. RedisPoolUtil.closeConn();
  97. }
  98. /**
  99. * kv对象取(json方式)
  100. * @param key
  101. * @param clazz反序列化对象类型
  102. * @return 对象
  103. * @author corleone
  104. * @date 2018年11月15日
  105. */
  106. @SuppressWarnings({ "unchecked" })
  107. public static <T> Object getObjectJson(String key,Class<?> clazz){
  108. Jedis jedis = RedisPoolUtil.getInstance();
  109. if(jedis==null){
  110. return null;
  111. }
  112. String result= jedis.get(key);
  113. RedisPoolUtil.closeConn();
  114. if(result==null){
  115. return null;
  116. }
  117. T obj=(T)JSON.parseObject(result,clazz);
  118. return obj;
  119. }
  120. /**
  121. * kv对象存(map形势)
  122. * @param key
  123. * @param u
  124. * @throws Exception
  125. * @author corleone
  126. * @date 2018年11月27日
  127. */
  128. public static void setObjectHash(String key, Object u) throws Exception {
  129. Jedis jedis = RedisPoolUtil.getInstance();
  130. if(jedis==null){
  131. return ;
  132. }
  133. jedis.hmset(key, MapUtil.objectToMap(u));
  134. RedisPoolUtil.closeConn();
  135. }
  136. /**
  137. * kv对象取(map形势)
  138. * @param key
  139. * @param clazz
  140. * @throws Exception
  141. * @author corleone
  142. * @date 2018年11月27日
  143. */
  144. public static Object getObjectHash(String key,Class<?> clazz) throws Exception {
  145. Jedis jedis = RedisPoolUtil.getInstance();
  146. if(jedis==null){
  147. return null;
  148. }
  149. Object obj = MapUtil.mapToObject(jedis.hgetAll(key), clazz);
  150. RedisPoolUtil.closeConn();
  151. if(obj==null){
  152. return null;
  153. }
  154. return obj;
  155. }
  156. }

7.User  Vehicle两个实体类  后者没有实现Serializable,不能用于java序列化存取

User

  1. package com.redis.test;
  2. import java.io.Serializable;
  3. /**
  4. * 用户实体类
  5. * @author corleone
  6. * @date 2018年11月27日
  7. */
  8. public class User implements Serializable {
  9. private static final long serialVersionUID = -3210884885630038713L;
  10. private int id;
  11. private String name;
  12. private int age;
  13. public User(){
  14. }
  15. public User(int id,String name,int age){
  16. this.id = id;
  17. this.name = name;
  18. this.age=age;
  19. }
  20. public int getId() {
  21. return id;
  22. }
  23. public void setId(int id) {
  24. this.id = id;
  25. }
  26. public String getName() {
  27. return name;
  28. }
  29. public void setName(String name) {
  30. this.name = name;
  31. }
  32. public int getAge() {
  33. return age;
  34. }
  35. public void setAge(int age) {
  36. this.age = age;
  37. }
  38. @Override
  39. public String toString() {
  40. return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
  41. }
  42. }

Vehicle

  1. package com.redis.test;
  2. /**
  3. * 车辆实体类
  4. * @author corleone
  5. * @date 2018年11月27日
  6. */
  7. public class Vehicle {
  8. private int id;
  9. private String platenumber;
  10. private String color;
  11. public Vehicle(){
  12. }
  13. public int getId() {
  14. return id;
  15. }
  16. public Vehicle(int id, String platenumber, String color) {
  17. this.id = id;
  18. this.platenumber = platenumber;
  19. this.color = color;
  20. }
  21. public void setId(int id) {
  22. this.id = id;
  23. }
  24. public String getPlatenumber() {
  25. return platenumber;
  26. }
  27. public void setPlatenumber(String platenumber) {
  28. this.platenumber = platenumber;
  29. }
  30. public String getColor() {
  31. return color;
  32. }
  33. public void setColor(String color) {
  34. this.color = color;
  35. }
  36. @Override
  37. public String toString() {
  38. return "Vehicle [id=" + id + ", platenumber=" + platenumber
  39. + ", color=" + color + "]";
  40. }
  41. }

8.JTest : jedis存取数据测试类

  1. package com.redis.test;
  2. import org.junit.Test;
  3. import redis.clients.jedis.Jedis;
  4. /**
  5. * jedis存取测试
  6. * @author corleone
  7. * @date 2018年11月27日
  8. */
  9. public class JTest {
  10. /**
  11. * 测试连接
  12. * @author corleone
  13. * @date 2018年11月27日
  14. */
  15. @Test
  16. public void TestPing(){
  17. Jedis jedis = RedisPoolUtil.getInstance();
  18. System.out.println(jedis.ping());
  19. }
  20. /**
  21. * 测试java序列化存取
  22. * @author corleone
  23. * @date 2018年11月27日
  24. */
  25. @Test
  26. public void TestSerialize(){
  27. User u = new User(1,"小明",6);
  28. RedisOps.setObjectSerialize(User.class.getName().toString()+":"+1, u);
  29. User u2 = (User)RedisOps.getObjectSerialize(User.class.getName().toString()+":"+1);
  30. System.out.println(u2.toString());
  31. }
  32. /**
  33. * 测试json序列化存取
  34. * @author corleone
  35. * @date 2018年11月27日
  36. */
  37. @Test
  38. public void TestJson(){
  39. User u = new User(1,"小明",6);
  40. Vehicle v = new Vehicle(1,"渝A00000","蓝色");
  41. RedisOps.setObjectJson(User.class.getName().toString()+":"+1, u);
  42. RedisOps.setObjectJson(Vehicle.class.getName().toString()+":"+1, v);
  43. User u2 = (User)RedisOps.<User>getObjectJson(User.class.getName().toString()+":"+1,User.class);
  44. Vehicle v2 = (Vehicle)RedisOps.<Vehicle>getObjectJson(Vehicle.class.getName().toString()+":"+1,Vehicle.class);
  45. System.out.println(u2.toString());
  46. System.out.println(v2.toString());
  47. }
  48. /**
  49. * 测试hash存取
  50. * @throws Exception
  51. * @author corleone
  52. * @date 2018年11月27日
  53. */
  54. @Test
  55. public void TestHash() throws Exception{
  56. Vehicle v = new Vehicle(1,"渝A00000","蓝色");
  57. RedisOps.setObjectHash(Vehicle.class.getName().toString()+":"+1, v);
  58. Vehicle v2=(Vehicle) RedisOps.getObjectHash(Vehicle.class.getName().toString()+":"+1,Vehicle.class);
  59. System.out.println(v2.toString());
  60. }
  61. }

五.连接测试

这里以json序列化存取对象为例

1.执行TestJson方法成功

2.查看redis中的数据

 六.注意事项

这里都是踩坑过来的,把我遇到过的问题也贴出来

1.外部无法连接:一般是linux防火墙未关闭的原因,这里特别注意centos7关闭防火墙与之前版本不一样,如果你用的centos7,那么请整对centos7进行百度

2.如果你的redis没有密码,请不要输入空字符串

3.java序列化存取对象,记得实现Serializable

4.如果你的实体类添加了有参构造方法,请重写无参构造方法,否则报如下错误

 

后续贴出springAOP实现redis连接,以及本人在实际业务中的存取方式,如有不足感谢指出!

   

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约