Jedis
Jedis是redis官方推荐的java连接开发工具,使用java操作redis中间件,如果要使用java操作redis就一定要对jedis十分熟悉。
测试
新建一个项目空项目
新建完毕创建一个module,完善项目信息。
修改这两个地方,jdk版本要选择自己环境配置的
然后选中一下这个java包,点击source以便后续使用
1、要使用jedis就要引入依赖
<!--导入jedis包-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.7.0</version>
</dependency>
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
2、编码测试
1)连接数据库
2)操作命令
3)断开连接
启动redis启动器,redis-server.exe
建包com.redis,建测试类TestPing
package com.redis;
import redis.clients.jedis.Jedis;
public class TestPing {
public static void main(String[] args) {
//1、new jedis对象
Jedis jedis = new Jedis("127.0.0.1",6379);
//2、jedis所有的命令就是之前学习的所有指令
System.out.println(jedis.ping());
}
}
运行,输出pong证明成功
点进源码查看
使用
package com.redis;
import redis.clients.jedis.Jedis;
import java.util.Set;
public class TestPing {
public static void main(String[] args) {
//1、new jedis对象
Jedis jedis = new Jedis("127.0.0.1",6379);
//2、jedis所有的命令就是之前学习的所有指令
System.out.println(jedis.ping());
System.out.println("清空数据:" +jedis.flushDB());
System.out.println("判断某个键是否存在:"+jedis.exists("username"));
System.out.println("新增<'username','changan'>的键值对:"+jedis.set("username","changan"));
System.out.println("新增<'password','password'>的键值对:"+jedis.set("password","password"));
System.out.println("系统中所有的建如下:");
Set<String> keys = jedis.keys("*");
System.out.println("删除键password:"+jedis.del("password"));
System.out.println("判断键password是否存在:" + jedis.exists("password"));
System.out.println("查看键username所存储的值的类型:" +jedis.type("username"));
System.out.println("随机返回key空间的一个:"+jedis.randomKey());
System.out.println("重命名key:"+jedis.rename("username","name"));
System.out.println("取出改后的name:"+jedis.get("name"));
System.out.println("按索引查询:"+jedis.select(0));
System.out.println("删除当前选择数据库中的所有key:"+jedis.flushDB());
System.out.println("返回当前数据库中key的数目:" +jedis.dbSize());
System.out.println("删除所有数据库中的所有key:" +jedis.flushAll());
}
}
由于redis不知如何在本地启动,试用过挺多的方法,所以这个图片截视频里面的图
常用的API
String
新建一个TestString类
package com.redis;
import redis.clients.jedis.Jedis;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public class TestString {
public static void main(String[] args) {
//1、new jedis对象
Jedis jedis = new Jedis("127.0.0.1",6379);
jedis.flushDB();
System.out.println("----------增加数据---------");
System.out.println(jedis.set("fkey","fvalue"));
System.out.println(jedis.set("skey","svalue"));
System.out.println(jedis.set("tkey","tvalue"));
System.out.println("删除键skey"+jedis.del("skey"));
System.out.println("获取键skey"+jedis.get("skey"));
System.out.println("修改fkey:"+jedis.set("fkey","changefvalue"));
System.out.println("获取fkey的值:"+jedis.get("fkey"));
System.out.println("在tkey后面加入值:"+jedis.append("tkey","jiarule"));
System.out.println("tkey的值:"+jedis.get("tkey"));
System.out.println("增加多个键值对:"+jedis.mset("key1","value1","key2","value2","key3","value3"));
System.out.println("获取多个键值对:"+jedis.mget("key1","key2","key3"));
System.out.println("获取多个键值对:"+jedis.mget("key1","key2","key3","key4"));
System.out.println("删除多个键值对:"+jedis.del("key3","key2"));
System.out.println("获取多个键值对:"+jedis.mget("key1","key2","key3"));
jedis.flushDB();
System.out.println("----------------新增键值对防止覆盖原先值-----------------");
System.out.println(jedis.setnx("key1","value1"));
System.out.println(jedis.setnx("key2","value2"));
System.out.println(jedis.setnx("key3","value2-nx"));
System.out.println(jedis.get("key1"));
System.out.println(jedis.get("key2"));
System.out.println("-------------新增键值对并设置有效时间-------------");
System.out.println(jedis.setex("key3",(long)4,"value3"));//如果不存在,4s后过期
System.out.println(jedis.get("key3"));
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(jedis.get("key3"));
System.out.println("---------------获取原值,更新为新值---------------");
System.out.println(jedis.getSet("key2","newkey2getset"));
System.out.println(jedis.get("key2"));
System.out.println("获得key2的值的字符串:"+jedis.getrange("key2",2,4));
}
}
运行结果
List
新建一个TestList类
package com.redis;
import redis.clients.jedis.Jedis;
import java.util.Set;
public class TestList {
public static void main(String[] args) {
//1、new jedis对象
Jedis jedis = new Jedis("127.0.0.1",6379);
jedis.flushDB();
System.out.println("-----------添加一个list-----------");
jedis.lpush("collections","ArrayList","Vactor","Stack","HashMap","WeakHashMap","LinkedHashMap");
jedis.lpush("collections","HashSet");
jedis.lpush("collections","TreeSet");
jedis.lpush("collections","TreeMap");
System.out.println("collections的内容,"+jedis.lrange("collections",0,-1));//-1代表倒数第一个元素,-2代表倒数第二个元素
System.out.println("collections区间[0,3]的元素:"+jedis.lrange("collections",0,3));
System.out.println("------------------------");
//删除列表指定的值,第二个参数为删除的个数(有重复时),后add进去的值先被删,类似于出栈
System.out.println("删除指定的元素个数,"+ jedis.lrem("collections",2,"HashMap"));
System.out.println("collections的内容: "+jedis.lrange("collections",0,-1));
//截取删除
System.out.println("删除下表区间[0,3]之外的元素:"+jedis.ltrim("collections",0,3));
System.out.println("collections的内容:"+jedis.lrange("collections",0,-1));
//弹出
System.out.println("collections列表出栈(左端):" + jedis.lpop("collections"));
System.out.println("collections的内容:"+jedis.lrange("collections",0,-1));
System.out.println("collections添加元素,从列表右端,与lpush相对应,"+jedis.rpush("collections","EnumMap"));
System.out.println("collections的内容:"+jedis.lrange("collections",0,-1));
System.out.println("collections列表出栈(右端):"+jedis.rpop("collections"));
System.out.println("collections的内容:"+jedis.lrange("collections",0,-1));
System.out.println("修改collections指定下标1的内容:"+jedis.lset("collections",1,"LinkedArrayList"));
System.out.println("collections的内容:"+jedis.lrange("collections",0,-1));
System.out.println("----------------------------");
System.out.println("collections的长度,"+jedis.llen("collections"));
//获取指定下标具体的值
System.out.println("获取collections下标为2的元素,"+jedis.lindex("collections",2));
System.out.println("----------------------------");
jedis.lpush("sortedList","2","5","8","4","6","7");
System.out.println("sortedList排序前:"+jedis.lrange("sortedList",0,-1));
System.out.println(jedis.sort("sortedList"));
System.out.println("sortedList排序后:"+jedis.lrange("sortedList",0,-1));
}
}
Set
新建一个TestSet类
package com.redis;
import redis.clients.jedis.Jedis;
public class TestSet {
public static void main(String[] args) {
//1、new jedis对象
Jedis jedis = new Jedis("127.0.0.1",6379);
jedis.flushDB();
System.out.println("------------------------");
System.out.println(jedis.sadd("eleSet","set1","set2","set3","set4","set0","set6","set2","set1"));
System.out.println(jedis.sadd("eleSet","set6"));
System.out.println(jedis.sadd("eleSet","set6"));
System.out.println("eleSet的所有元素为:"+jedis.smembers("eleSet"));
System.out.println("删除一份元素set0:"+jedis.srem("eleSet","set0"));
System.out.println("eleSet的所有元素为:"+jedis.smembers("eleSet"));
System.out.println("随机的移除集合中的一个元素:"+jedis.spop("eleSet"));
System.out.println("随机的移除集合中的一个元素:"+jedis.spop("eleSet"));
System.out.println("eleSet的所有元素为:"+jedis.smembers("eleSet"));
System.out.println("eleSet中包含元素的个数:"+jedis.scard("eleSet"));
System.out.println("set3是否在eleSet中:"+jedis.sismember("eleSet","set3"));
System.out.println("set1是否在eleSet中:"+jedis.sismember("eleSet","set1"));
System.out.println("set5是否在eleSet中:"+jedis.sismember("eleSet","set5"));
System.out.println("---------------------------");
System.out.println(jedis.sadd("eleSet1","set1","set2","set5","set8","set4","set","set0"));
System.out.println(jedis.sadd("eleSet2","set1","set2","set4","set0","set8"));
System.out.println("将eleSet1中删除set1并存入eleSet3中:"+jedis.smove("eleSet1","eleSet3","set1"));
System.out.println("将eleSet1中删除set2并存入eleSet3中:"+jedis.smove("eleSet1","eleSet3","set2"));
System.out.println("eleSet1中的元素:"+ jedis.smembers("eleSet1"));
System.out.println("eleSet3中的元素:"+ jedis.smembers("eleSet3"));
System.out.println("--------------集合运算-------------");
System.out.println("eleSet1中的元素:" + jedis.smembers("eleSet1"));
System.out.println("eleSet2中的元素:" + jedis.smembers("eleSet2"));
System.out.println("eleSet1和eleSet2的交集:"+ jedis.sinter("eleSet1","eleSet2"));
System.out.println("eleSet1和eleSet2的并集:"+ jedis.sunion("eleSet1","eleSet2"));
//eleSet中有,eleSet2中没有
System.out.println("eleSet1和eleSet2的差集:"+ jedis.sdiff("eleSet1","eleSet2"));
//求交集并将交集保存到dstkey的集合
jedis.sinterstore("eleSet4","eleSet1","eleSet2");
System.out.println("eleSet4中的元素:"+jedis.smembers("eleSet4"));
}
}
Hash
新建一个TestHash类
package com.redis;
import redis.clients.jedis.Jedis;
import java.util.HashMap;
import java.util.Map;
public class TestHash {
public static void main(String[] args) {
//1、new jedis对象
Jedis jedis = new Jedis("127.0.0.1",6379);
jedis.flushDB();
Map<String,String> map = new HashMap<>();
map.put("key1","value1");
map.put("key2","value2");
map.put("key3","value3");
map.put("key4","value4");
//添加名称为hash(key)的hash元素
jedis.hmset("hash",map);
//向名称为hash的hash中添加key为key5,value为value5的元素
jedis.hset("hash","key5","value5");
//return Map<String,String>
System.out.println("散列hash的所有键值对为:"+jedis.hgetAll("hash"));
//return Map<String>
System.out.println("散列hash的所有键为:"+jedis.hkeys("hash"));
//return List<String,String>
System.out.println("散列hash的所有值为:"+jedis.hvals("hash"));
System.out.println("将key6保存的值加上一个整数,如果key6不存在则添加key6:"+jedis.hincrBy("key6","value6",2));
System.out.println("散列hash的所有键值对为:"+jedis.hgetAll("hash"));
System.out.println("将key6保存的值加上一个整数,如果key6不存在则添加key6:"+jedis.hincrBy("key6","value6",1));
System.out.println("散列hash的所有键值对为:"+jedis.hgetAll("hash"));
System.out.println("删除一个或者多个键值对:"+jedis.hdel("hash","hey2"));
System.out.println("散列hash的所有键值对为:"+jedis.hgetAll("hash"));
System.out.println("散列hash中键值对的个数:"+jedis.hgetAll("hash"));
System.out.println("判断hash中是否存在key2:"+jedis.hexists("hash","key2"));
System.out.println("判断hash中是否存在key3:"+jedis.hexists("hash","key3"));
System.out.println("获取hash中的值:"+jedis.hmget("hash","key3"));
System.out.println("获取hash中的值:"+jedis.hmget("hash","key3","key4"));
}
}
Zset
Jedis事务
新建一个TestTX类
package com.redis;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
public class TestTX {
public static void main(String[] args) {
Jedis jedis = new Jedis("127.0.0.1",6379);
jedis.flushDB();
JSONObject jsonObject = new JSONObject();
jsonObject.put("2021","11/22");
jsonObject.put("age","3000");
//开启事务
Transaction multi = jedis.multi();
String result = jsonObject.toJSONString();
try{
multi.set("user1",result);
multi.set("user2",result);
//代码抛出异常,事务执行失败
int i = 1/0;
//执行事务
multi.exec();
}catch (Exception e){
//放弃事务
multi.discard();
e.printStackTrace();
}finally {
System.out.println(jedis.get("user1"));
System.out.println(jedis.get("user2"));
//关闭连接
jedis.close();
}
}
}
SpringBoot整合Redis
Springboot操作数据:spring-data jpa MongoDB redis
SpringData也是和springboot齐名的项目
新建一个springboot的module
说明:在SpringBoot2.x后,原来使用的jedis被替换为了lettuce。
Jedis:底层采用的是直连,多个线程操作的话,是不安全的,如果想要避免不安全的,使用jedis pool连接池。BIO
Lettuce:底层采用netty,实例可以在多个线程中进行共享,不存在线程不安全的情况,可以减少线程数据了,更像NIO模式
源码解释:搜索RedisAutoConfiguration.class,进源码查看
@Bean
//我们可以自己定义一个redisTemplate来替换这个默认的
@ConditionalOnMissingBean(
name = {"redisTemplate"}
)
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
//默认的RedisTemplate 没有过多的设置,redis对象都是需要序列化
//两个泛型都是Object, Object的类型,我们后面使用需要强制转换<String, Object>
RedisTemplate<Object, Object> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean
@ConditionalOnMissingBean //由于String类型是redis中最常用的类型,所以说单独提出来了一个bean
@ConditionalOnSingleCandidate(RedisConnectionFactory.class)
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
整合测试
项目结构
1、 导入依赖
<!--操作redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、 写配置(properties)
# 配置redis连接
spring.redis.host=127.0.0.1
spring.redis.port=6379
3、 测试类
package com.project;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootTest
class Redis02SpringbootApplicationTests {
@Autowired
//@Qualifier("redisTemplate")
private RedisTemplate redisTemplate;
@Test
void contextLoads() {
/**
* 在企业开发中,我们80%的情况下,不会使用这个原生的方式去编写代码
* 封装成一个工具类:RedisUtils
*/
//redisTemplate 操作不同的数据类型,api和我们的指令是一样的
//opsForValue 操作字符串,类似String
//opsForList 操作List,类似List
//opsForSet
//opsForHash
//opsForZSet
//opsForGeo
//opsForHyperLogLog
//除了基本的操作,常用的方法都可以直接通过redisTemplate操作,比如事务和基本的CRUD(增删查改)
//获取redis的连接对象
//RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
//connection.flushDb();
//connection.flushAll();
redisTemplate.opsForValue().set("mykey","undergraduate");
System.out.println(redisTemplate.opsForValue().get("mykey"));
}
@Test
public void boredom() throws JsonProcessingException {
//一般真实的开发一般都使用json来传递对象
User user = new User("vast and hazy",17);
String jsonUser = new ObjectMapper().writeValueAsString(user);
//redisTemplate.opsForValue().set("user",jsonUser);
redisTemplate.opsForValue().set("user",user);
System.out.println(redisTemplate.opsForValue().get("user"));
}
}
Pojo中的User
package com.project.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;
import java.io.Serializable;
@Component
@Data
@AllArgsConstructor //有参,需要在idea中下载Lombok插件
@NoArgsConstructor
//在企业中,所有的pojo类都会序列化(Serializable) springboot
public class User implements Serializable {
private String name;
private int age;
}
4、自定义redisTemplate,新建一个redisconfig的类
package com.project.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
//配置类
@Configuration
public class RedisConfig {
// 编写自己的redisTemplate
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
//方便自己开发,一般直接使用<String, Object>类型
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
//连接工厂
template.setConnectionFactory(factory);
//Json 序列化配置
Jackson2JsonRedisSerializer objectJackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//转义
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//“enableDefaultTyping (com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping)”是弃用
//使用{@link #activateDefaultTyping(多态typevalidator,DefaultTyping)}代替
// objectMapper.activateDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
objectJackson2JsonRedisSerializer.setObjectMapper(objectMapper);
//String 的序列化
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//key采用string的序列化方式
template.setKeySerializer(stringRedisSerializer);
//hash的key也采用string的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
//value序列化方式采用Jackson
template.setValueSerializer(objectJackson2JsonRedisSerializer);
//hash的value序列化方式采用jackson
template.setHashValueSerializer(objectJackson2JsonRedisSerializer);
//把所有方法set进去
template.afterPropertiesSet();
//配置具体的序列化方式
// template.setKeySerializer(objectJackson2JsonRedisSerializer);
// template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
运行的时候确保redis是连接上的。
封装RedisUtils,这个在公司中会有自己的一个封装工具
所有的redis操作对于java开发人员来说更重要的是要去理解redis的思想和每一种数据结构的用处和作用