经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » Redis » 查看文章
Scala 操作Redis使用连接池工具类RedisUtil
来源:jb51  时间:2019/6/19 13:12:25  对本文有异议

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

  1. package com.zjw.util
  2.  
  3. import java.util
  4.  
  5. import org.apache.commons.pool2.impl.GenericObjectPoolConfig
  6. import org.apache.logging.log4j.scala.Logging
  7. import redis.clients.jedis.{Jedis, JedisPool, Response}
  8. import redis.clients.util.Pool
  9.  
  10. object RedisUtil extends Logging {
  11. private[this] var jedisPool: Pool[Jedis] = _
  12.  
  13. def main(args: Array[String]): Unit = {
  14. val password = "h-{<Fc!yJL87_Zkc8S"
  15. val host = "192.168.100.101"
  16. val port = 6379
  17. val timeout = 1000
  18. RedisUtil.init(host, port, timeout, password, 0)
  19. //RedisUtil.set("Time".getBytes(), "2018-09-03 09:00:00".getBytes())
  20. //val result = RedisUtil.get("Time".getBytes())
  21. //println(new String(result))
  22. //val map = Map("name"-> "zhangsan","age"-> "21", "gender"-> "male", "id"-> "519099386")
  23. //RedisUtil.setCols("hash",map)
  24.  
  25. // val result = RedisUtil.getCols("hash", Array("name", "age", "xx")).map(x => (x._1, new String(x._2)))
  26. // logger.info(result)
  27. val result = RedisUtil.bulkGetCols(Array("hash", "ss"))
  28. logger.info(s"result: ${result}")
  29. }
  30.  
  31. def init(host: String, port: Int, timeout: Int, password: String, database: Int = 0): Unit = {
  32. jedisPool = new JedisPool(new GenericObjectPoolConfig, host, port, timeout, password, database)
  33. }
  34.  
  35. def get(key: Array[Byte]): Array[Byte] = {
  36. val jedis = jedisPool.getResource
  37. val result: Array[Byte] = jedis.get(key)
  38. jedis.close()
  39. result
  40. }
  41.  
  42. def set(key: Array[Byte], value: Array[Byte]): Boolean = {
  43. try {
  44. val jedis = jedisPool.getResource
  45. jedis.set(key, value)
  46. jedis.close()
  47. true
  48. } catch {
  49. case e: Exception => {
  50. logger.error(s"写入数据到Redis出错: ${e}")
  51. false
  52. }
  53. }
  54. }
  55.  
  56.  
  57. def getCols(key: String,
  58. cols: Array[String] = Array.empty
  59. ): Map[String, Array[Byte]] = {
  60. import scala.collection.JavaConverters._
  61. val jedis = jedisPool.getResource
  62. var map = Map.empty[String, Array[Byte]]
  63. if (cols.length > 0) {
  64. val pipe = jedis.pipelined()
  65. val response = pipe.hmget(key.getBytes(), cols.map(_.getBytes()): _*)
  66. pipe.sync()
  67. map = cols.zip(response.get.asScala).toMap.filter(x => x._2 != null)
  68. pipe.close()
  69. } else {
  70. logger.info(s"key: ${key}")
  71. val tmpMap: util.Map[Array[Byte], Array[Byte]] = jedis.hgetAll(key.getBytes())
  72. map = tmpMap.asScala.toMap.map(x => (new String(x._1), x._2))
  73. }
  74. jedis.close
  75. map
  76. }
  77.  
  78. def getCols2(
  79. key: String,
  80. cols: Array[String] = Array.empty
  81. ): Map[String, Array[Byte]] = {
  82. val jedis = jedisPool.getResource
  83. var map = Map.empty[String, Array[Byte]]
  84. if (cols.length > 0) {
  85. for (col <- cols) {
  86. val value: Array[Byte] = jedis.hget(key.getBytes(), col.getBytes())
  87. if (null != value) {
  88. map = map + (col -> value)
  89. }
  90. }
  91. } else {
  92. logger.info(s"rowkey: ${key}")
  93. val tmpMap: util.Map[Array[Byte], Array[Byte]] = jedis.hgetAll(key.getBytes())
  94. import scala.collection.JavaConverters._
  95. map = tmpMap.asScala.toMap.map(x => (new String(x._1), x._2))
  96. }
  97. jedis.close
  98. map
  99. }
  100.  
  101. def bulkGetCols(keys: Array[String],
  102. cols: Array[String] = Array.empty
  103. ): Map[String, Map[String, Array[Byte]]] = {
  104. import scala.collection.JavaConverters._
  105. var result: Map[String, Map[String, Array[Byte]]] = Map.empty
  106. val jedis = jedisPool.getResource
  107. val pipe = jedis.pipelined
  108. if (cols.length > 0) {
  109. val data = keys.map(x => {
  110. pipe.hmget(x.getBytes(), cols.map(_.getBytes()): _*)
  111. })
  112.  
  113. pipe.sync
  114. pipe.close
  115. jedis.close
  116.  
  117. result = keys.zip(data.map(_.get().asScala.toArray).map(cols.zip(_).toMap.filter(null != _._2)))
  118. .toMap.filter(_._2.nonEmpty)
  119. } else {
  120. val data: Array[Response[util.Map[Array[Byte], Array[Byte]]]] = keys.map(x => {
  121. pipe.hgetAll(x.getBytes())
  122. })
  123. pipe.sync
  124. pipe.close
  125. jedis.close
  126.  
  127. result = keys.zip(data.map(_.get().asScala.map(x => (new String(x._1), x._2)).toMap))
  128. .toMap.filter(_._2.nonEmpty)
  129. }
  130. result
  131. }
  132.  
  133. def bulkGetCols2(rowkeys: Array[String],
  134. cols: Array[String] = Array.empty
  135. ): Map[String, Map[String, Array[Byte]]] = {
  136. val jedis = jedisPool.getResource
  137. var map = Map.empty[String, Map[String, Array[Byte]]]
  138. import scala.collection.JavaConverters._
  139. for (rowkey <- rowkeys) {
  140. var cellMap = Map.empty[String, Array[Byte]]
  141. if (cols.length > 0) {
  142. for (col <- cols) {
  143. val value = jedis.hget(rowkey.getBytes(), col.getBytes())
  144. if (null != value) {
  145. cellMap = cellMap + (col -> value)
  146. }
  147. }
  148. } else {
  149. logger.info(s"rowkey: ${rowkey}")
  150. val tmpMap = jedis.hgetAll(rowkey.getBytes())
  151. cellMap = tmpMap.asScala.toMap.map(x => (new String(x._1), x._2))
  152. }
  153. if (cellMap.nonEmpty) {
  154. map = map + (rowkey -> cellMap)
  155. }
  156. }
  157. jedis.close
  158. map
  159. }
  160.  
  161. def setCols(
  162. key: String,
  163. fieldValues: Map[String, String]
  164. ): Unit = {
  165. import scala.collection.JavaConverters._
  166. val data = fieldValues.map(element => {
  167. (element._1.getBytes(), element._2.getBytes())
  168. }).asJava
  169. val jedis = jedisPool.getResource
  170. jedis.hmset(key.getBytes(), data)
  171. jedis.close()
  172. }
  173.  
  174. }
  175.  

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

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号