scala中使用redis


redis命令參考網址:http://doc.redisfans.com/index.html

創建redis集群:

import java.util.Properties
import java.io.FileInputStream
import java.util
import redis.clients.jedis.{HostAndPort, JedisCluster}
import org.apache.commons.pool2.impl.GenericObjectPoolConfig

object RedisUtil {
  private val propertiesPath = "/home/..." //配置文件本地地址
  private val properties = new Properties()
  properties.load(new FileInputStream(propertiesPath))
  private val jedisClusterNodes = new util.HashSet[HostAndPort]()
  private val IP = properties.getProperty("redisIP")
  private val redis_passwd = properties.getProperty("redis_passwd")
  private val ports = properties.getProperty("RedisPorts").split(",")
  for (i <- 0 until ports.size){
    jedisClusterNodes.add(new HostAndPort(IP,ports(i).toInt))
  }

  var cluster:JedisCluster = _

  def createJedisCluster(connecitonTimeout:Int = 60000,
                         soTimeout:Int = 60000,
                         maxAttempts:Int = 5):JedisCluster = {
    if (cluster == null){
      cluster = new JedisCluster(jedisClusterNodes, connecitonTimeout, soTimeout,maxAttempts,redis_passwd,new GenericObjectPoolConfig())
      cluster
    }
    cluster
  }
}

  

key鍵操作:

//刪除key
cluster.del(key)
//判斷key是否存在
cluster.exists(key)

  

list列表操作:

#key的value添加元素
cluster.lpush(key,value) //列表左添加
cluster.rpush(key,value) //列表右添加
#取出指定范圍內的元素-閉區間,包括stop
cluster.lrange(key,start,stop) //start從0開始,-1表示列表最后一個元素,-2表示列表倒數第二個元素
//時間復雜度: O(S+N), S 為偏移量 start , N 為指定區間內元素的數量。
#取出全部元素
cluster.lrange(key,0,-1) //返回一個列表
#將列表 key 下標為 index 的元素的值設置為 value
cluster.lset(key,index,value)

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM