jedis 实战使用
jedis 基本操作
- jedis
- spring data redis
- 和springboot整合
- redisTemplate 使用
- redis 的集中基本数据类型使用
- 注解式使用
- @Cacheable
- @CachePut
- @CacheEvict
- @Caching
- @CacheConfig
- 结合redis 使用
jedis
因为jedis 对实际开发已经没有任何意义了,基本上都是用 spring data redis 的 api。
spring data redis
spring-data-reids 提供了spring应用中通过简单的配置访问redis服务,对redis底层开发包进行了高度封装
redisTemplate 提供了redis各种操作,异常处理序列化
- 连接池自动管理,提供了一个高度封装的 redisTemplate 类
- 针对jedis 客户端中大量api 进行了归类封装,将同一类型操作封装为operation 接口。
和springboot整合
后续整理
redisTemplate 使用
和 redisTemplate 一样的还有StringRedisTemplate,StringRedisTemplate 是继承 redisTemplate ,但两者的数据是不共通的
。
redisTemplate 常用的操作
- bound***Ops
- opsFor***
- delete
主要开发中用于数据的存取,和修改,参考以下
redis 的集中基本数据类型使用
@Testpublic void testString(){// 实例化一个对象BoundValueOperations<String, Serializable> value = redisTemplate.boundValueOps("name");// set 添加value.set("lisi");// get 查找Serializable name = value.get();System.out.println("当前的姓名"+ name);// append (测试下来,并没有往value 后面添加值,所以自己也不确定是否用错)value.append(" is a bad man"); // 返回值是 Integer 类型Serializable newName = value.get();System.out.println("当前键:"+ value.getKey() + ", 当前姓名:" + newName); // 当前键:name, 当前姓名:lisi// set 添加超时时间value.set("wangwu",6,TimeUnit.HOURS);System.out.println("被修改的值:"+value.get()); // 被修改的值:wangwu//Set the bound key to hold the string value if the bound key is absent.//如果绑定键不存在,则设置绑定键来保存字符串值System.out.println("绑定键是否存在:"+value.setIfAbsent("haha")); // false//Set the bound key to hold the string value if key is present.//如果键存在,则设置绑定键来保存字符串值。System.out.println("绑定键是否存在:"+value.setIfPresent("zhangsan"));
// System.out.println("绑定键是否存在:"+value.setIfPresent("wangwu"));System.out.println("现在的值:"+value.get()); //zhangsan}// Hash 类型操作@Testpublic void testHash(){// 实例化一个 Hash 对象BoundHashOperations<String, Object, Object> person = redisTemplate.boundHashOps("person");//设置值Map map = new HashMap();map.put("name","lisi");map.put("age",3);map.put("sex","man");person.putAll(map);//获取Map<Object, Object> entries = person.entries();System.out.println(entries);// 单个keyObject name = person.get("name");System.out.println("name:"+name);//hasKey 是否存在System.out.println(person.hasKey("name"));// 所有keySystem.out.println(person.keys());// 获取大于1 的keyList list = new ArrayList();list.add("name");list.add("sex");List personValuelist = person.multiGet(list);System.out.println(personValuelist);// 判断key是否存在,不存在则添加person.putIfAbsent("loveGirl","haha");// values 获取所有值System.out.println(person.values());//[haha, 3, lisi, man]}//测试List@Testpublic void testList(){redisTemplate.delete("fruits");BoundListOperations<String, Serializable> fruits = redisTemplate.boundListOps("fruits");fruits.leftPush("apple");fruits.leftPush("banana");System.out.println(fruits.getOperations()); // org.springframework.data.redis.core.RedisTemplate@4e212f46// 返回整个数组System.out.println("返回所有数组:"+fruits.range(0,-1));//左边移掉一个System.out.println( fruits.leftPop()); // 返回移掉的值// key 存在就添加System.out.println(fruits.leftPushIfPresent("apple"));System.out.println(fruits.leftPushIfPresent("banana"));System.out.println("返回所有数组:"+fruits.range(0,-1)); //返回所有数组:[banana, apple, apple]// 移除 2 个 applefruits.remove(2,"apple");System.out.println("返回所有数组:"+fruits.range(0,-1)); // 返回所有数组:[banana, apple]}// set 值不可重复@Testpublic void testSet(){redisTemplate.delete("fruits");redisTemplate.delete("sweetfruits");BoundSetOperations<String, Serializable> fruits = redisTemplate.boundSetOps("fruits");BoundSetOperations<String, Serializable> sweetfruits = redisTemplate.boundSetOps("sweetfruits");// 添加fruits.add("apple","pineapple");fruits.add("banana");fruits.add("apple");sweetfruits.add("apple");// 获取
// Set<Serializable> members = fruits.members();
// System.out.println("fruits 的集合:"+members);// [pineapple, banana, apple]//比较不同 diff(Collection<K> keys) , diff(K key) 返回比较中sweetfruits没有的值而fruits 中有的值
// System.out.println("fruits 的 diff :"+ fruits.diff( "sweetfruits")); // [pineapple, banana]sweetfruits.add("kiwi fruit");
// System.out.println("sweetfruits 的集合:"+ sweetfruits.members());// [kiwi fruit, apple]//diffAndStore(Collection<K> keys, K destKey)BoundSetOperations<String, Serializable> difffruits = redisTemplate.boundSetOps("difffruits");fruits.diffAndStore("fruits","sweetfruits");redisTemplate.opsForSet().members("sweetfruits").forEach(v -> System.out.println("比较不同set并存储:" + v));System.out.println("difffruits 的集合:" + difffruits.members());System.out.println("sweetfruits 的集合:" + sweetfruits.members());// [] , 会把后面的函数清空System.out.println("fruits 的集合:" + fruits.members());}
注解式使用
开启基于注解的缓存 @EnableCaching
一些缓存注解
@Cacheable
// key 生存策略,参考下图
@Cacheable(cacheNames = "test", key ="#id" )
public Person get(Long id){// ...
}
上述就已经完成了spring本地化的缓存
自定义生成key 策略的实现
@Cacheable(cacheNames = "test", keyGenerator ="myKeyGenerate" )
@Configuration
public class MyCacheConfig {@Bean("myKeyGenerate")public KeyGenerator myKeyGenerate(){return new KeyGenerator() {@Overridepublic Object generate(Object o, Method method, Object... objects) {return method.getName() +"["+ objects[0].toString()+"]";}};}
}
缓存中用到的spel表达式
@CachePut
修改了数据库的某个数据,同时更新缓存
@CachePut(cacheNames = "test", key ="#test.id")
@Override
public Test update(Test test) {testMapper.updateById(test);return test;
}
@CacheEvict
删除缓存中的数据
@CacheEvict(cacheNames = "test",key = "#id") // beforeInvocation 无论是否有异常,都会清除缓存
@Override
public void del(Long id) {System.out.println("将要删除的:"+id);
}
@Caching
复合注解(实际开发中,暂时没用到过)
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Caching {Cacheable[] cacheable() default {};CachePut[] put() default {};CacheEvict[] evict() default {};
}
@CacheConfig
抽取缓存公共的配置
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CacheConfig {String[] cacheNames() default {};String keyGenerator() default "";String cacheManager() default "";String cacheResolver() default "";
}
结合redis 使用
加入redis 后,发现spring 自动使用了redis 缓存了。
springboot2.0+
实现注解存放redis中序列化和反序列化
//缓存管理器
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ZERO).serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer())).serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer())).disableCachingNullValues();RedisCacheManager redisCacheManager = RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(config).transactionAware().build();return redisCacheManager;
}
jedis 实战使用相关推荐
- Redis实战之征服 Redis + Jedis + Spring (三)
一开始以为Spring下操作哈希表,列表,真就是那么土.恍惚间发现"stringRedisTemplate.opsForList()"的强大,抓紧时间恶补下. 通过spring-d ...
- Redis实战之Redis + Jedis
用Memcached,对于缓存对象大小有要求,单个对象不得大于1MB,且不支持复杂的数据类型,譬如SET 等.基于这些限制,有必要考虑Redis! 相关链接: Redis实战 Redis实战之Redi ...
- Jedis的hincrBy方法实战
Jedis的hincrBy方法实战 解决方法: dbindex 数据库索引,相当数据库的名称 mapName map的名字,相当表名 key map里面的key count:增量,也可以为负数 详情 ...
- Flink / Scala 实战 - 6.使用 Jedis、JedisPool 作为 Source 读取数据
一.引言 现在有一批数据写入多台 Redis 相同 key 的队列中,需要消费 Redis 队列作为 Flink Source,为了提高可用性,下面基于 JedisPool 进行队列的消费.队列数据示 ...
- Redis实战(八):面试常问:击穿,穿透,雪崩,分布式锁,API(jedis,luttce,springboot:low/high level)
缓存击穿 作为缓存,受到内存大小限制,可能: key 超过了过期时间 key 被 LRU LFU 清掉了 因为某些 key 不在 redis 里面了,大量并发来找这个 key 的时候,这时候客户端去直 ...
- Spring4实战学习笔记
<Spring4实战 第4版>2016年4月新出版的,之前的第三版看起来还是不错的,所以看到新版就直接买下来. 英文版源码地址:Spring in Action, Fourth Editi ...
- 实战 用户登录、session校验、分布式存储session
实现登录功能 然后再创建login.css存放于在static下,css目录中,id 为 content 的 样式: #content {margin-left: 220px;margin-right ...
- 分布式爬虫系统设计、实现与实战:爬取京东、苏宁易购全网手机商品数据+MySQL、HBase存储...
http://blog.51cto.com/xpleaf/2093952 1 概述 在不用爬虫框架的情况,经过多方学习,尝试实现了一个分布式爬虫系统,并且可以将数据保存到不同地方,类似MySQL.HB ...
- Java Spring Data Redis实战与配置参数详解 application.properties...
Redis作为开源分布式高并发缓存,使用范围非常广泛,主流互联网公司几乎都在使用. Java Spring Boot 2.0实战开发Redis缓存可以参考下面的步骤,Redis安装可以直接使用Linu ...
最新文章
- 构建弹性架构组件—ELB和ASG
- 【转】在html中引入CSS的方法
- Luogu 1941 飞扬的小鸟
- 网站开发技巧参考大全转
- 进制转换问题---例如把26进制转为10进制
- python标准库之logging
- linux 限速命令,Linux下网卡限速
- 设计模式(7) 续原型模式
- Python使用matplotlib可视化模拟烧烤摊每月营业额折线图
- VS 2022 SVN 插件
- zoom在win7上安装失败
- Android图片加载框架最全解析(八),带你全面了解Glide 4的用法
- lambda学习视频和stream学习视频(Java8 Lambda表达式视频教程)-Java爬虫-网络购物的正确打开方式
- 大数据开发薪资水平怎么样?
- 三维几何 --- 计算几何模板
- dos2unix命令找不到怎么办
- sketch怎么转换成html,手稿秒变html的Sketch 2 Code
- 哪些行业可以申请高新技术企业?
- 知网上的论文怎么下载成word格式
- 电子元器件图片、名称、符号,超全面+唯样商城