Java与redis连接的驱动主流的Jedis
Spring提供RedisConnectionFactory接口→通过它可以生成RedisConnection接口对象→RedisConnection接口对象对Redis底层接口的封装进行操作。(本次使用的为Jedis驱动,那么就会提供RedisConnection接口的实现类JedisConnection去封装原有的Jedis)
图展示
RedisTemplate其会自动从RedisConnectionFactory获取连接,对redis进行操作,使用最频繁。
在pom.xml添加依赖
org.springframework.boot
spring-boot-starter-data-redis
io.lettuce
lettuce-core
redis.clients
jedis
Redis进行配置,并设置连接
package com.springboot.chapter7.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
public class RedisConfig {
private RedisConnectionFactory connectionFactory = null; //用于连接
@Bean(name = "RedisConnectionFactory")
public RedisConnectionFactory initConnectionFactory(){
if(this.connectionFactory != null){
return this.connectionFactory;
}
JedisPoolConfig poolConfig = new JedisPoolConfig(); //java与Redis的链接驱动Jedis的配置
//最大空闲数
poolConfig.setMaxIdle(30);
//最大连接数
poolConfig.setMaxTotal(50);
//最大等待毫秒数
poolConfig.setMaxWaitMillis(2000);
//创建Jedis连接工厂
JedisConnectionFactory connectionFactory = new JedisConnectionFactory(poolConfig); //JedisConnectionFactory的实现类
//配置redis连接服务器
RedisStandaloneConfiguration rscfg = connectionFactory.getStandaloneConfiguration();
rscfg.setHostName("192.168.1.4");
rscfg.setPassword("123456");
rscfg.setPort(6379);
this.connectionFactory =connectionFactory;
return connectionFactory;
}
@Bean("redisTemplate")
public RedisTemplate
实现
package com.springboot.chapter7;
import com.springboot.chapter7.config.RedisConfig;
import org.apache.catalina.core.ApplicationContext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootApplication
public class Chapter7Application {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(RedisConfig.class); //构造自己的IoC容器
RedisTemplate redisTemplate = ctx.getBean(RedisTemplate.class);
redisTemplate.opsForValue().set("key2","value1");
redisTemplate.opsForHash().put("hash","field","hvalue");
SpringApplication.run(Chapter7Application.class, args);
}
}
通过set(“key2”,“value1”)将字符串传入,Java是面向对象的编程语言,Redis是一种基于字符串存储的NoSQL,因此只要类实现了java.io.Serializable接口,就代表类的对象能够进行序列化,通过将类对象进行序列化能够得到二进制字符串,这样Redis就可以将这些类对象以字符串进行存储了。同时Java也可以将那些二进制字符串通过反序列化转为对象。
通过这个原理,Spring提供了在initRedisTemplate方法中的RedisSerializer接口,该接口有两个方法。
查看redis的路径,进入其目录下
/usr/local/redis/redis-5.0.8/src/redis-cli -h localhost -p 6379 -a 123456
localhost:6379> get key2
"\xac\xed\x00\x05t\x00\x06value1"
localhost:6379> hget hash field
"hvalue"
spring.redis.jedis.pool.max-idle=5
spring.redis.jedis.pool.max-active=10
spring.redis.jedis.pool.min-idle=10
spring.redis.jedis.pool.max-wait=2000
#配置Redis服务器属性
spring.redis.port=6379
spring.redis.host=192.168.1.4
#redis连接超时时间,单位为毫秒
spring.redis.timeout=1000
将其转化为字符串
package com.springboot.chapter7.main;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import javax.annotation.PostConstruct;
@SpringBootApplication(scanBasePackages = "com.springboot.chapter7")
public class Chapter7Application {
//注入RedisTemplate
@Autowired
private RedisTemplate redisTemplate = null;
//定义自定义后初试方法
@PostConstruct
public void init(){
initRedisTemplate();
}
//设置redisTemplate的序列化器
private void initRedisTemplate(){
RedisSerializer serializer = redisTemplate.getStringSerializer();//RedisTemplate会自定义一个StringRedisSerializer对象
redisTemplate.setKeySerializer(serializer);
redisTemplate.setHashKeySerializer(serializer);
}
public static void main(String[] args) {
SpringApplication.run(Chapter7Application.class,args);
}
}
注释已经介绍很详细
package com.springboot.chapter7.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Controller
@RequestMapping("/redis")
public class RedisController {
@Autowired
private RedisTemplate redisTemplate = null;
@Autowired
private StringRedisTemplate stringRedisTemplate = null;
//操作redis字符串和散列数据类型
@RequestMapping("/stringAndHash")
@ResponseBody
public Map testStringAndHash(){
redisTemplate.opsForValue().set("key1","value1");
//注意这里使用了JDK的序列器,所以Redis服务器保存的不是整数,不能运算
redisTemplate.opsForValue().set("int_key",1);
//克服不能运算的问题,利用StringRedisTemplate就可以克服这个问题
stringRedisTemplate.opsForValue().set("int","1");
//使用运算
stringRedisTemplate.opsForValue().increment("int",1);
//因为RedisTemplate不支持redis的所有命令,所以获取底层Jedis连接,利用其进行操作
Jedis jedis = (Jedis)stringRedisTemplate.getConnectionFactory().getConnection().getNativeConnection();
//减一操作,这个命令RedisTemplate不支持,所以先获取底层的连接等操作
jedis.decr("int");
Map hash = new HashMap();
hash.put("field1","value1");
hash.put("field2","value2");
//存入一个散列数据类型
stringRedisTemplate.opsForHash().putAll("hash",hash);
//新增一个字段
stringRedisTemplate.opsForHash().put("hash","field3","value3");
//绑定散列操作的key,这样可以联系对同一个散列数据类型进行操作
BoundHashOperations hashOperations = stringRedisTemplate.boundHashOps("hash");
//删除两个字段
hashOperations.delete("field1","field2");
//新增第一个字段
hashOperations.put("field4","value4");
Map map = new HashMap();
map.put("success",true);
return map;
}
//使用Spring操作列表(链表)
@RequestMapping("/list")
@ResponseBody
public Map testList(){
//插入两个列表,注意它们在链表的顺序
//链表从右到左的顺序,v10,v8,v6,v4,v2
stringRedisTemplate.opsForList().leftPushAll(
"list1","v2","v4","v6","v8","v10"
);
//从左到右
stringRedisTemplate.opsForList().leftPushAll(
"list2","v1","v2","v3","v4","v5","v6"
);
//绑定list2操作
BoundListOperations listOperations = stringRedisTemplate.boundListOps("list2");
//从右边弹出一个成员
Object result1 = listOperations.rightPop();
//获取坐标,从0开始,所以这个值为v2
Object result2 = listOperations.index(1);
//从左边插入链表
listOperations.leftPush("v0");
//求链表长度
Long size = listOperations.size();
//求链表下标区间成员,整个链表下标范围为0到size-1,这里不取最后一个元素
List elements = listOperations.range(0,size-2);
Map map = new HashMap();
map.put("success",true);
return map;
}
//使用Spring操作集合
@RequestMapping("/set")
@ResponseBody
public Map testSet(){
stringRedisTemplate.opsForSet().add("set1","v1","v1","v2","v3","v4","v6","v7");
stringRedisTemplate.opsForSet().add("set2","v2","v4","v6","v8");
//绑定Set1集合操作
BoundSetOperations setOperations = stringRedisTemplate.boundSetOps("set1");
//增加两个元素
setOperations.add("v6","v8");
//删除两个元素
setOperations.remove("v1","v7");
//返回所有元素
Set set = setOperations.members();
//成员数
Long size = setOperations.size();
//求交集
Set inter = setOperations.intersect("set2");
//求交集,并用新集合inter保存
setOperations.intersectAndStore("set2","inter");
//求差集
Set diff = setOperations.diff("set2");
//求差集,并保存到diff
setOperations.diffAndStore("set2","diff");
//求并集
Set union = setOperations.union("set2");
//并保存
setOperations.unionAndStore("set2","union");
Map map = new HashMap();
map.put("Success",true);
return map;
}
}
localhost:6379> smembers set1
1) "v8"
2) "v6"
3) "v3"
4) "v4"
5) "v2"
localhost:6379> lrange list2 0 -1
1) "v0"
2) "v6"
3) "v5"
4) "v4"
5) "v3"
6) "v2"
localhost:6379> hgetall hash
1) "field"
2) "hvalue2"
3) "field3"
4) "value3"
5) "field4"
6) "value4"
localhost:6379> get int
"1"