欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Scala 操作Redis使用连接池工具类RedisUtil

程序员文章站 2022-04-25 20:19:42
本文介绍了scala 操作redis,分享给大家,具体如下: package com.zjw.util import java.util import...

本文介绍了scala 操作redis,分享给大家,具体如下:

package com.zjw.util

import java.util

import org.apache.commons.pool2.impl.genericobjectpoolconfig
import org.apache.logging.log4j.scala.logging
import redis.clients.jedis.{jedis, jedispool, response}
import redis.clients.util.pool

object redisutil extends logging {
 private[this] var jedispool: pool[jedis] = _

 def main(args: array[string]): unit = {
  val password = "h-{<fc!yjl87_zkc8s"
  val host = "192.168.100.101"
  val port = 6379
  val timeout = 1000
  redisutil.init(host, port, timeout, password, 0)
  //redisutil.set("time".getbytes(), "2018-09-03 09:00:00".getbytes())
  //val result = redisutil.get("time".getbytes())
  //println(new string(result))
  //val map = map("name"-> "zhangsan","age"-> "21", "gender"-> "male", "id"-> "519099386")
  //redisutil.setcols("hash",map)

  // val result = redisutil.getcols("hash", array("name", "age", "xx")).map(x => (x._1, new string(x._2)))
  // logger.info(result)
  val result = redisutil.bulkgetcols(array("hash", "ss"))
  logger.info(s"result: ${result}")
 }

 def init(host: string, port: int, timeout: int, password: string, database: int = 0): unit = {
  jedispool = new jedispool(new genericobjectpoolconfig, host, port, timeout, password, database)
 }

 def get(key: array[byte]): array[byte] = {
  val jedis = jedispool.getresource
  val result: array[byte] = jedis.get(key)
  jedis.close()
  result
 }

 def set(key: array[byte], value: array[byte]): boolean = {
  try {
   val jedis = jedispool.getresource
   jedis.set(key, value)
   jedis.close()
   true
  } catch {
   case e: exception => {
    logger.error(s"写入数据到redis出错: ${e}")
    false
   }
  }
 }


 def getcols(key: string,
       cols: array[string] = array.empty
       ): map[string, array[byte]] = {
  import scala.collection.javaconverters._
  val jedis = jedispool.getresource
  var map = map.empty[string, array[byte]]
  if (cols.length > 0) {
   val pipe = jedis.pipelined()
   val response = pipe.hmget(key.getbytes(), cols.map(_.getbytes()): _*)
   pipe.sync()
   map = cols.zip(response.get.asscala).tomap.filter(x => x._2 != null)
   pipe.close()
  } else {
   logger.info(s"key: ${key}")
   val tmpmap: util.map[array[byte], array[byte]] = jedis.hgetall(key.getbytes())
   map = tmpmap.asscala.tomap.map(x => (new string(x._1), x._2))
  }
  jedis.close
  map
 }

 def getcols2(
        key: string,
        cols: array[string] = array.empty
       ): map[string, array[byte]] = {
  val jedis = jedispool.getresource
  var map = map.empty[string, array[byte]]
  if (cols.length > 0) {
   for (col <- cols) {
    val value: array[byte] = jedis.hget(key.getbytes(), col.getbytes())
    if (null != value) {
     map = map + (col -> value)
    }
   }
  } else {
   logger.info(s"rowkey: ${key}")
   val tmpmap: util.map[array[byte], array[byte]] = jedis.hgetall(key.getbytes())
   import scala.collection.javaconverters._
   map = tmpmap.asscala.tomap.map(x => (new string(x._1), x._2))
  }
  jedis.close
  map
 }

 def bulkgetcols(keys: array[string],
         cols: array[string] = array.empty
         ): map[string, map[string, array[byte]]] = {
  import scala.collection.javaconverters._
  var result: map[string, map[string, array[byte]]] = map.empty
  val jedis = jedispool.getresource
  val pipe = jedis.pipelined
  if (cols.length > 0) {
   val data = keys.map(x => {
    pipe.hmget(x.getbytes(), cols.map(_.getbytes()): _*)
   })

   pipe.sync
   pipe.close
   jedis.close

   result = keys.zip(data.map(_.get().asscala.toarray).map(cols.zip(_).tomap.filter(null != _._2)))
    .tomap.filter(_._2.nonempty)
  } else {
   val data: array[response[util.map[array[byte], array[byte]]]] = keys.map(x => {
    pipe.hgetall(x.getbytes())
   })
   pipe.sync
   pipe.close
   jedis.close

   result = keys.zip(data.map(_.get().asscala.map(x => (new string(x._1), x._2)).tomap))
    .tomap.filter(_._2.nonempty)
  }
  result
 }

 def bulkgetcols2(rowkeys: array[string],
         cols: array[string] = array.empty
         ): map[string, map[string, array[byte]]] = {
  val jedis = jedispool.getresource
  var map = map.empty[string, map[string, array[byte]]]
  import scala.collection.javaconverters._
  for (rowkey <- rowkeys) {
   var cellmap = map.empty[string, array[byte]]
   if (cols.length > 0) {
    for (col <- cols) {
     val value = jedis.hget(rowkey.getbytes(), col.getbytes())
     if (null != value) {
      cellmap = cellmap + (col -> value)
     }
    }
   } else {
    logger.info(s"rowkey: ${rowkey}")
    val tmpmap = jedis.hgetall(rowkey.getbytes())
    cellmap = tmpmap.asscala.tomap.map(x => (new string(x._1), x._2))
   }
   if (cellmap.nonempty) {
    map = map + (rowkey -> cellmap)
   }
  }
  jedis.close
  map
 }

 def setcols(
        key: string,
        fieldvalues: map[string, string]
       ): unit = {
  import scala.collection.javaconverters._
  val data = fieldvalues.map(element => {
   (element._1.getbytes(), element._2.getbytes())
  }).asjava
  val jedis = jedispool.getresource
  jedis.hmset(key.getbytes(), data)
  jedis.close()
 }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。