IDEA配置Redis及简单运用

2022-06-29 13:08:28

前提:已安装Redis,导入jedis.jar,commons-pool2.jar

<dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>2.8.0</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId><version>2.4.2</version></dependency>

配置连接池RedisUtils.java

publicclassRedisUtils{privatestaticJedisPool jedisPool;static{//创建properties文件Properties properties=newProperties();//读取配置文件InputStream is=RedisUtils.class.getResourceAsStream("jedis.properties");//加载配置文件try{
            properties.load(is);}catch(IOException e){
            e.printStackTrace();}//System.out.println(properties.getProperty("host"));//创建连接池对象JedisPoolConfig config=newJedisPoolConfig();//最大允许连接数
        config.setMaxTotal(Integer.parseInt(properties.getProperty("maxTotal")));//最大空闲连接数
        config.setMaxIdle(Integer.parseInt(properties.getProperty("maxIdle")));//创建jedisPool连接池对象 timeout客户端超时时间
        jedisPool=newJedisPool(config,properties.getProperty("host"),Integer.parseInt(properties.getProperty("port")),3000,properties.getProperty("password"));/*
       无密码:JedisPool(config,properties.getProperty("host"),Integer.parseInt(properties.getProperty("port")));
        */}//返回数据连接池publicstaticJedisPooljedisPool(){return jedisPool;}//返回Jedis连接publicstaticJedisgetJedis(){return jedisPool.getResource();}//关闭资源publicstaticvoidgetClose(Jedis jedis){if(jedis!=null){
            jedis.close();}}publicstaticvoidgetClose(JedisPool jedisPool){if(jedisPool!=null){
            jedisPool.close();}}}

RedisJDBCTest.java

publicclassRedisJDBCTest{publicstaticvoidmain(String[] args){//建立一个连接Jedis jedis=RedisUtils.getJedis();//操作listfor(int i=1;i<6;i++){
            jedis.rpush("sum",i+"");//右边开始添加//jedis.lpush()//左边开始添加}
        jedis.lpop("sum");//删除并返回左边第一个元素
        jedis.rpop("sum");//删除并返回右边第一个元素
        jedis.lrem("sum",0,"2");//count=0删除全部value为2,count>0从头开始删除value=2数量为count,count<0从尾开始开始删除value=2数量为countSystem.out.println(jedis.lrange("sum",0,5));//取第1~6值System.out.println(jedis.llen("sum"));//长度// set
        jedis.sadd("person","学生");
        jedis.sadd("person","艺术","美术");System.out.println(jedis.smembers("person"));//hash
         jedis.hset("hash","k1","v1");
         jedis.hset("hash","k2","v2");//删除键值对
        jedis.hdel("hash","k1");//取出所有value,返回list<string>System.out.println(jedis.hvals("hash"));//取出指定key的valueSystem.out.println(jedis.hget("hash","k2"));//取出所有key-value,map类型System.out.println(jedis.hgetAll("hash"));//jedis.del("name");//关闭资源RedisUtils.getClose(jedis);}}

jedis.properties

host=127.0.0.1
port=6379
password=123456
maxTotal=20
maxIdle=10
  • 作者:绘云
  • 原文链接:https://blog.csdn.net/qq_46089556/article/details/122194395
    更新时间:2022-06-29 13:08:28