1、导入redis的客户端jedis
<!--导入redis的客户端jedis jar包-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.1</version>
</dependency>
linux开启redis
开启redis: /opt/apps/redis/redis-server redis.conf
开启客户端: redis-cli –h 192.168.42.101
密码:auth 123456
2、redis实现事务
pipeline可以将所有的操作当成一个整体,不过只支持单机
import com.sparkstreaming.utils._01_JedisConnectionPool
import redis.clients.jedis.Jedis
object _05_JedisPipeline {
def main(args: Array[String]): Unit = {
//普通创建redis
/* val jedis = new Jedis("192.168.42.101",6379)
jedis.auth("123456") //指定密码
jedis.select(1)*/
val jedis = _01_JedisConnectionPool.getConnection
jedis.select(1)
//让redis支持事务,pipeline可以将所有的操作当成一个整体,不过只支持单机
val pipeline = jedis.pipelined()
pipeline.multi() //开启多个操作,将所有的操作当成一个整体
try {
pipeline.hset("WC", "java", "10")
pipeline.hset("WC", "hive", "10")
//val i = 100 / 0
//提交
pipeline.exec()
pipeline.sync()
} catch {
case e:Exception =>
//回滚
pipeline.discard()
} finally {
if(pipeline != null) pipeline.close()
if(jedis != null) jedis.close()
}
}
}
工具类
import com.sparkstreaming.utils.JedisConnectionPool.config
import redis.clients.jedis.{Jedis, JedisPool, JedisPoolConfig}
object _01_JedisConnectionPool {
//jedisPool的配置
private val config = new JedisPoolConfig()
//池子里最多的对象数量
config.setMaxTotal(5)
//池子里面最大的活跃对象
config.setMaxIdle(2)
//对连接进行检测,看看是否有效
config.setTestOnBorrow(true)
//创建jedisPool
private val jedisPool = new JedisPool(config, "192.168.42.101",
6379, 10000, "123456")
//单例创建对象
def getConnection: Jedis = {
jedisPool.getResource
}
}