jedis使用

引入依赖

<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.6.0</version>
		</dependency>

  

 

例子一:

public static void main(String[] args) {
        // 构造jedis对象
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        // 向redis中添加数据
        jedis.set("mytest", "123");
        // 从redis中读取数据
        String value = jedis.get("mytest");

        System.out.println(value);
        // 关闭连接
        jedis.close();

    }

  

例子二,连接池:

 public static void main(String[] args) {
        // 构建连接池配置信息
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // 设置最大连接数
        jedisPoolConfig.setMaxTotal(50);

        // 构建连接池
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, "127.0.0.1", 6379);

        // 从连接池中获取连接
        Jedis jedis = jedisPool.getResource();

        // 读取数据
        System.out.println(jedis.get("mytest"));

        // 将连接还回到连接池中
        jedisPool.returnResource(jedis);

        // 释放连接池
        jedisPool.close();

    }

  

连接池:分片集群:

public static void main(String args[]){
		//构建连接池配置
		JedisPoolConfig poolConfig = new JedisPoolConfig();
		//连接池配置
		poolConfig.setMaxTotal(50);
		
		//定义集群信息
		List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
		shards.add(new JedisShardInfo("127.0.0.1", 6379));
		
		//定义集群连接池
		ShardedJedisPool jedisPool = new ShardedJedisPool(poolConfig, shards);
		ShardedJedis shardedJedis = null;
		try {
			//从连接池中获取分片信息
			shardedJedis = jedisPool.getResource();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally{
			//将连接池放回到连接池中
			if(null != shardedJedis){
				shardedJedis.close();
			}
			//关闭连接池
			jedisPool.close();
		}
		
		
		
		
	}

  

 

相关文章:

  • 2021-11-14
  • 2021-09-17
  • 2022-12-23
  • 2021-09-13
  • 2021-07-31
  • 2022-12-23
  • 2022-02-23
  • 2021-12-25
猜你喜欢
  • 2022-12-23
  • 2021-07-23
  • 2021-12-21
  • 2022-12-23
  • 2021-07-28
  • 2022-12-23
  • 2021-07-17
相关资源
相似解决方案