远程连接Jedis和整合SpringBoot的详细过程
作者:@烟雨倾城ゝ
这篇文章主要介绍了远程连接Jedis和整合SpringBoot的详细过程,本文通过图文实例相结合给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
一、远程连接Jedis
1、导入Jedis所需的jar包
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency>
2、远程连接Redis注意事项
- 禁用Linux的防火墙:systemctl stop/disable firewalld.service
- 在配置文件redis.conf中注释掉bind 127.0.0.1 ,然后修改protected-mode no
3、Jedis测试远程连接
package com.hcz; import redis.clients.jedis.Jedis; public class TestPing { public static void main(String[] args) { Jedis jedis = new Jedis("49.236.195.225",6379); System.out.println("连接成功:"+jedis.ping()); jedis.close(); } }
4、常用的数据类型
(1)Key
package com.hcz; import redis.clients.jedis.Jedis; import java.util.Set; public class TestKey { public static void main(String[] args) { Jedis jedis = new Jedis("49.236.195.225",6379); System.out.println("连接成功:"+jedis.ping()); System.out.println("清空数据:"+jedis.flushDB()); System.out.println("判断某个键知否存在:"+jedis.exists("username")); System.out.println("新增<'username','hcz'>的键值对"+jedis.set("username","hcz")); System.out.println("新增<'password','123'>的键值对"+jedis.set("password","123")); System.out.println("系统中所有的键如下:"); Set<String> keys = jedis.keys("*"); System.out.println(keys); System.out.println("获取username的值:"+jedis.get("username")); System.out.println("获取password的值:"+jedis.get("password")); 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","newname")); System.out.println("取出重命名后的newname:"+jedis.get("newname")); System.out.println("按索引查询:"+jedis.select(0)); System.out.println("清空当前数据库所有的key:"+jedis.flushDB()); System.out.println("返回当前数据库中key的数目:"+jedis.dbSize()); System.out.println("删除所有数据库中的key:"+jedis.flushAll()); jedis.close(); } }
(2)String
package com.hcz; import redis.clients.jedis.Jedis; import java.util.Set; import java.util.concurrent.TimeUnit; public class TestString { public static void main(String[] args) { Jedis jedis = new Jedis("139.196.236.217",6379); System.out.println("连接成功:"+jedis.ping()); System.out.println("清空数据:"+jedis.flushDB()); System.out.println("====增加数据===="); System.out.println(jedis.set("k1","v1")); System.out.println(jedis.set("k2","v2")); System.out.println(jedis.set("k3","v3")); System.out.println("删除键k2:"+jedis.del("k2")); System.out.println("获取键k2:"+jedis.get("k2")); System.out.println("获取键k1:"+jedis.get("k1")); System.out.println("修改键k3:"+jedis.set("k3","new_v3")); System.out.println("获取k3的值:"+jedis.get("k3")); System.out.println("在k3后面加值:"+jedis.append("k3","End")); System.out.println("获取k3的值:"+jedis.get("k3")); System.out.println("增加多个键值对:"+jedis.mset("k4","v4","k5","v5")); System.out.println("获取多个键值对:"+jedis.mget("k3","k4","k5")); System.out.println("删除多个键值对:"+jedis.del("k1","k3")); System.out.println("清空数据:"+jedis.flushDB()); System.out.println("====新增键值对防止覆盖原先值===="); System.out.println(jedis.setnx("k1","v1")); System.out.println(jedis.setnx("k2","v2")); System.out.println(jedis.setnx("k2","v2-new")); System.out.println("获取k1的值"+jedis.get("k1")); System.out.println("获取k2的值"+jedis.get("k2")); System.out.println("====新增键值并设置有效时间===="); System.out.println(jedis.setex("k3",2,"v3")); System.out.println("第一次获取k3的值"+jedis.get("k3")); try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("第二次获取k3的值"+jedis.get("k3")); System.out.println("====获取原值,更新为新值====="); System.out.println(jedis.getSet("k2","k2-getset")); System.out.println(jedis.get("k2")); System.out.println("获得k2的值的字串:"+jedis.getrange("k2",2,4)); jedis.close(); } }
(3)List
package com.hcz; import redis.clients.jedis.Jedis; public class TestList { public static void main(String[] args) { Jedis jedis = new Jedis("49.236.195.225",6379); System.out.println("连接成功:"+jedis.ping()); System.out.println("清空数据:"+jedis.flushDB()); System.out.println("====增加一个list===="); jedis.lpush("collections","ArrayList","Vector","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)); 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("collections列表出栈(左端):"+jedis.lpop("collections")); System.out.println("collections的内容:"+jedis.lrange("collections",0,-1)); System.out.println("collections添加元素,从列表右端,与lpush相对应:"+jedis.rpush("collections","List","Set","String")); 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,"newHashSet")); 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("sortList","3","5","2","8","6","0"); System.out.println("sortList排序前:"+jedis.lrange("sortList",0,-1)); System.out.println(jedis.sort("sortList")); System.out.println("sortList排序后:"+jedis.lrange("sortList",0,-1)); jedis.close(); } }
(4)Set
package com.hcz; import redis.clients.jedis.Jedis; import java.util.Set; public class TestSet { public static void main(String[] args) { Jedis jedis = new Jedis("49.236.195.225",6379); System.out.println("连接成功:"+jedis.ping()); System.out.println("清空数据:"+jedis.flushDB()); System.out.println("==========向集合中添加元素(不重复)"); System.out.println(jedis.sadd("eleSet","e1","e0","e3","e6","e5","e7","e8")); System.out.println(jedis.sadd("eleSet","e4")); System.out.println(jedis.sadd("eleSet","e4")); System.out.println("eleSet的所有元素为:"+jedis.smembers("eleSet")); System.out.println("删除一个元素e0:"+jedis.srem("eleSet","e0")); System.out.println("eleSet的所有元素为:"+jedis.smembers("eleSet")); System.out.println("删除二个元素e7,e6:"+jedis.srem("eleSet","e7","e6")); 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("e3是否存在eleSet中:"+jedis.sismember("eleSet","e3")); System.out.println("e1是否存在eleSet中:"+jedis.sismember("eleSet","e1")); System.out.println("e5是否存在eleSet中:"+jedis.sismember("eleSet","e5")); System.out.println("=============================="); System.out.println(jedis.sadd("eleSet1","e1","e0","e3","e6","e5","e7","e8")); System.out.println(jedis.sadd("eleSet2","e1","e0","e3","e6","e8")); System.out.println("将eleSet1删除e1并存入eleSet3中:"+jedis.smove("eleSet1","eleSet3","e1")); System.out.println("将eleSet1删除e2并存入eleSet3中:"+jedis.smove("eleSet1","eleSet3","e2")); 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")); System.out.println("eleSet1和eleSet2的差集:"+jedis.sdiff("eleSet1","eleSet2")); jedis.sinterstore("eleSet4","eleSet1","eleSet2");//求交集并保存到eleSet4中 System.out.println("eleSet4的所有元素为:"+jedis.smembers("eleSet4")); jedis.close(); } }
(5)Hash
package com.hcz; import redis.clients.jedis.Jedis; import java.util.HashMap; import java.util.Map; public class TestHash { public static void main(String[] args) { Jedis jedis = new Jedis("49.236.195.225",6379); System.out.println("连接成功:"+jedis.ping()); System.out.println("清空数据:"+jedis.flushDB()); Map<String,String> map = new HashMap<>(); map.put("key1","v1"); map.put("key2","v2"); map.put("key3","v3"); map.put("key4","v4"); //添加名称为hash的hash元素 jedis.hmset("hash",map); //向名称为hash的hash中添加key为key5,value为v5元素 jedis.hset("hash","key5","v5"); System.out.println("散列hash的所有键值对为:"+jedis.hgetAll("hash")); System.out.println("散列hash的所有键为:"+jedis.hkeys("hash")); System.out.println("散列hash的所有值为:"+jedis.hvals("hash")); System.out.println("将key6保存的值加上一个整数,如果key6不存在则添加key6:"+jedis.hincrBy("hash","key6",4)); System.out.println("散列hash的所有键值对为:"+jedis.hgetAll("hash")); System.out.println("删除一个或者多个键值对:"+jedis.hdel("hash","key2","key4")); System.out.println("散列hash的所有键值对为:"+jedis.hgetAll("hash")); System.out.println("散列hash的所有键值对个数为:"+jedis.hlen("hash")); System.out.println("判断hash中是否存在key2:"+jedis.hexists("hash","key2")); System.out.println("判断hash中是否存在key3:"+jedis.hexists("hash","key3")); System.out.println("获取hash中的值:"+jedis.hget("hash","key3")); System.out.println("获取hash中的值:"+jedis.hmget("hash","key3","key5")); jedis.close(); } }
5、Jedis实现事务
(1)事务正常执行
public class TestMulti { public static void main(String[] args) { Jedis jedis = new Jedis("49.236.195.225",6379); System.out.println("连接成功:"+jedis.ping()); System.out.println("清空数据:"+jedis.flushDB()); JSONObject jsonObject = new JSONObject(); jsonObject.put("hello","world"); jsonObject.put("name","hcz"); //开启事务 Transaction multi = jedis.multi(); String result = jsonObject.toJSONString(); try { multi.set("user1",result); multi.set("user2",result); multi.exec();//执行事务 }catch (Exception e){ multi.discard();//放弃事务 e.printStackTrace(); }finally { System.out.println("user1为:"+jedis.get("user1")); System.out.println("user2为:"+jedis.get("user2")); jedis.close();//关闭连接 } } }
(2)事务编译时异常
public class TestMulti { public static void main(String[] args) { Jedis jedis = new Jedis("49.236.195.225",6379); System.out.println("连接成功:"+jedis.ping()); System.out.println("清空数据:"+jedis.flushDB()); JSONObject jsonObject = new JSONObject(); jsonObject.put("hello","world"); jsonObject.put("name","hcz"); //开启事务 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("user1为:"+jedis.get("user1")); System.out.println("user2为:"+jedis.get("user2")); jedis.close();//关闭连接 } } }
二、整合SpringBoot
1、导入依赖
说明:
在SpringBoot2.x之后,原来使用的jedis被替换为了lettuce
jedis:采用直连,多个线程操作的话是不安全的,如果想要避免不安全,可以使用 jedis pool连接池!更像BIO模式lettuce:采用netty,实例可以再多个线程共享,不存在线程不安全的情况,可以减少线程数据!更像NIO模式
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2、配置连接
spring: redis: host: 49.236.195.225 #远程主机名 port: 6379 #端口号 jedis: pool: max-active: 8 max-wait: -1ms max-idle: 500 min-idle: 0 lettuce: shutdown-timeout: 0ms
3、测试连接
@SpringBootTest class SpringbootRedisApplicationTests { @Autowired private RedisTemplate redisTemplate; @Test void contextLoads() { //redisTemplate //opsForValue 操作字符串 类似String //opsForList 操作List 类型List //opsForSet //opsForHash //opsForZSet //opsForGeo //opsForHyperLogLog //获取连接对象 RedisConnection connection = redisTemplate.getConnectionFactory().getConnection(); connection.flushDb(); //connection.flushAll(); redisTemplate.opsForValue().set("myKey","myValue"); System.out.println(redisTemplate.opsForValue().get("myKey")); } }
4、序列化
@Component @AllArgsConstructor @NoArgsConstructor @Data //在企业中,我们所有的pojo都会序列化 public class User implements Serializable { private String name; private int age; }
@Autowired private RedisTemplate redisTemplate; @Test public void test(){ try { //真实开发一般使用json来传递对象 User user = new User("张三 ", 18); //String jsonUser = new ObjectMapper().writeValueAsString(user); redisTemplate.opsForValue().set("user",user); System.out.println(redisTemplate.opsForValue().get("user")); } catch (JsonProcessingException e) { e.printStackTrace(); } }
5、自定义序列化
@Configuration public class RedisConfig { //自定义了一个RedisTemplate @Bean @SuppressWarnings("all") public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { //为了开发方便,一般使用<String, Object> RedisTemplate<String, Object> template = new RedisTemplate<String, Object>(); template.setConnectionFactory(factory); //Json序列化配置 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); //String的序列化 StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); // key采用String的序列化方式 template.setKeySerializer(stringRedisSerializer); // hash的key也采用String的序列化方式 template.setHashKeySerializer(stringRedisSerializer); // value序列化方式采用jackson template.setValueSerializer(jackson2JsonRedisSerializer); // hash的value序列化方式采用jackson template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } }
6、自定义工具类
自定义工具类的好处:
已经帮我们将原生的redisTemplate.opsForValue().set() 复杂命令封装成一些简单的命令
@Component public final class RedisUtil { @Autowired private RedisTemplate<String, Object> redisTemplate; // =============================common============================ /** * 指定缓存失效时间 * @param key 键 * @param time 时间(秒) */ public boolean expire(String key, long time) { try { if (time > 0) { redisTemplate.expire(key, time, TimeUnit.SECONDS); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } …………省略后面一大堆代码…………
7、再次进行测试
@Autowired private RedisUtil redisUtil; @Test public void test2(){ redisUtil.set("username","hcz"); System.out.println(redisUtil.get("username")); redisUtil.hset("hash","age",18); System.out.println(redisUtil.hget("hash","age")); redisUtil.hincr("hash","age",5); System.out.println(redisUtil.hget("hash","age")); }
到此这篇关于远程连接Jedis和整合SpringBoot的详细过程的文章就介绍到这了,更多相关Jedis和SpringBoot整合内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!