本文共 2423 字,大约阅读时间需要 8 分钟。
Spring针对Redis的使用,封装了一个比较强大的Template以方便使用;
RedisTemplate访问Redis数据结构(一)——String/List/Hash/Set/ZSet
首先初始化spring工厂获得redisTemplate和opsForHash
常用集合:https://www.iteye.com/blog/357029540-2389150 //建立map集合 Map<String, String> map=new HashMap<>();private RedisTemplateredisTemplate;private HashOperations opsForHash;param.put("key1", "a");param.put("key2", "b");param.put("key3", "c");param.put("key4", 4);opsForHash.putAll("he3", param); //存储hash对象redisTemplate.opsForSet().add("set_eq_settings",motorId);System.out.println(opsForHash.increment("he3", "key4", 1));//5System.out.println(opsForHash.hasKey("he", "key2"));//false hasKeySystem.out.println(opsForHash.get("he5", "key1"));//aopsForHash.delete("he3", "key1");opsForHash.put("he1", "key3", "c");Map entries = opsForHash.entries("he1");keys.add("key1");//multiGetkeys.add("key");keys.add("key2");System.out.println(opsForHash.multiGet("he6", keys))System.out.println(opsForHash.putIfAbsent("he10", "key1", "a"));//true
————————————————使用
System.out.println(opsForHash.size("he9"));//5Setkeys = opsForHash.keys("he8");for (Object key : keys) { Object value = redisMap.get("eq_status_"+motorId, key); System.out.println((String) key+":"+(String) value); switch ((String)key){ case "speed" : { if(value!=null) motorStatus.setSpeed(Integer.parseInt(((String)value).trim())); break; } Set
pom.xml:redis.properties:设置redis配置spring-redis.xml org.springframework.boot spring-boot-starter-data-redis
通过pipeline方式当有大批量的操作时候,我们可以节省很多原来浪费在网络延迟的时间,需要注意到是用pipeline方式打包命令发送,redis必须在处理完所有命令前先缓存起所有命令的处理结果。service调用:
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;@Resourcepublic JedisConnectionFactory jedisConnectionFactory;private static Jedis jedis; if (jedis == null) { jedis = (Jedis)jedisConnectionFactory.getConnection().getNativeConnection(); }
转载地址:http://tlhdi.baihongyu.com/