• jedis连接redis


    1. package com.wsd;
    2. import redis.clients.jedis.Jedis;
    3. import java.io.IOException;
    4. import java.io.InputStream;
    5. import java.util.HashMap;
    6. import java.util.Map;
    7. import java.util.Properties;
    8. public class Redis {
    9. public static void main(String[] args) {
    10. //读取properties file
    11. String fileName = "redis.properties";
    12. Map<String,String> map = getProperties(fileName);
    13. String host = map.get("host");
    14. int port = Integer.valueOf( map.get("port") );
    15. String auth = map.get("auth");
    16. int select = Integer.valueOf( map.get("select") );
    17. //连接redis
    18. Jedis jedis = new Jedis(host, port);
    19. //设置密码
    20. jedis.auth(auth);
    21. //选择库
    22. jedis.select(select);
    23. //执行set命令
    24. String OK = jedis.set("name","罗小黑");
    25. System.out.println(OK);
    26. //执行get命令
    27. String name = jedis.get("name");
    28. System.out.println("name=" + name);
    29. if(jedis != null)
    30. jedis.close();
    31. }
    32. private static Map<String,String> getProperties(String fileName){
    33. Map<String,String> map = new HashMap<>();
    34. Properties properties = new Properties();
    35. InputStream inputStream = null;
    36. try{
    37. //读取properties file
    38. inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
    39. properties.load(inputStream);
    40. String host = properties.getProperty("host");
    41. String port = properties.getProperty("port");
    42. String auth = properties.getProperty("auth");
    43. String select = properties.getProperty("select");
    44. map.put("host",host);
    45. map.put("port",port);
    46. map.put("auth",auth);
    47. map.put("select",select);
    48. }catch (IOException ex){
    49. System.out.println("read file:" + fileName + " fail");
    50. }finally {
    51. if(inputStream != null);
    52. try {
    53. inputStream.close();
    54. } catch (IOException e) {
    55. e.printStackTrace();
    56. }
    57. }
    58. return map;
    59. }
    60. }

     

  • 相关阅读:
    Git 入门 拉取仓库和推送仓库
    Django 自定义用户 VS 用户资料
    leetcode 周赛 364
    进行 Spring 6 迁移的最佳方式
    maven
    将JavaBean交给IoC容器管理和依赖注入DI
    【操作系统 | Linux】 文件管理四件套(切换,创建删除,复制移动)
    计算机网络原理 网络层
    3.7 学会这2招,让你的笔记分分钟上热门 【玩赚小红书】
    Redis代码实践总结(二)
  • 原文地址:https://blog.csdn.net/weixin_41812346/article/details/134442334