Redis初始化配置及增删改查
package com.calc.tools import redis.clients.jedis.JedisPool import redis.clients.jedis.Jedis import redis.clients.jedis.JedisPoolConfig import java.util.HashMap object Redis { var shardedJedisPool: JedisPool = null var shardedJedis: Jedis = null var ADDR: String = "" //redis ip address var AUTH: String = "" //redis password var PORT: Int = 6379 //redis port 默认6379 val TIMEOUT: Int = 10000 def initRedis() { val config: JedisPoolConfig = new JedisPoolConfig(); config.setMaxTotal(100); config.setMaxIdle(10); config.setMaxWaitMillis(-1); config.setTestOnBorrow(true); shardedJedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH); shardedJedis = shardedJedisPool.getResource } /** * 获取redis中key对应的所有数据 */ def getAllKeys(key: String) { initRedis() println(shardedJedis.hkeys(key)) shardedJedisPool.returnResourceObject(shardedJedis) } /** * 删除redis中key对应的所有数据 */ def deleteAll(key: String) { initRedis() shardedJedis.del(key) shardedJedisPool.returnResourceObject(shardedJedis) } /** * 将String的数据存放到到redis中 */ def insertRedisDo(key: String, field: String, value: String): Long = { initRedis() var ret: Long = shardedJedis.hset(key, field, value) shardedJedisPool.returnResourceObject(shardedJedis) return ret } /** * 将hashmap集合中的数据存放到到redis中 * * */ def insertRedisByHashmap(key: String, map: HashMap[String, String]) { initRedis() shardedJedis.hmset(key, map) shardedJedisPool.returnResource(shardedJedis); } def main(args: Array[String]): Unit = { val key: String = "I love you !" val field: String = "add this field ! " val value: String = "this is value into redis !" //插入字符串到redis 如果key和field在redis中已存在,则覆盖,相当月更新功能 println(insertRedisDo(key, field, value)) var map: HashMap[String, String] = new HashMap[String, String] map.put("field1", "value1") map.put("field2", "value2") //批量插入HashMap到redis println(insertRedisByHashmap(key, map)) //删除key下所有数据 println(deleteAll(key)) //获取key下所有数据 getAllKeys(key) } }
其中,ADDR是redis服务器的地址;AUTH是redis的独立密码。
完成。