赞
踩
目录
Redisson - 是一个高级的分布式协调Redis客服端,能帮助用户在分布式环境中轻松实现一些Java的对象。Redisson、Jedis、Lettuce 是三个常用的操作 Redis 的客户端,Jedis、Lettuce 的 API 更侧重对 Reids 数据库的 CRUD(增删改查);而 Redisson API 侧重于分布式开发,提供了多种分布式Java对象和服务,包括分布式锁、分布式集合、分布式对象、分布式限流器、可重入锁等。
Redisson是一个在Redis的基础上实现的Java内存数据网格(In-Memory Data Grid),它充分利用了Redis键值数据库提供的一系列优势,基于Java实用工具包中常用接口,为使用者提供了一系列具有分布式特性的常用工具类,让使用Redis更加简单、便捷,从而让使用者能够将更多精力集中到业务逻辑处理上。
也就是说Redisson不仅仅是一个Redis客户端,它是一个以内存 Redis 服务器作为后端的处理 Java 对象,它还实现了很多具有分布式特性的常用工具类。比如分布式锁、布隆过滤器等。下图是官网提供的Redisson可以做的事情。
- <dependency>
- <groupId>org.redisson</groupId>
- <artifactId>redisson</artifactId>
- <version>3.15.5</version>
- </dependency>
- <dependency>
- <groupId>org.redisson</groupId>
- <artifactId>redisson-spring-boot-starter</artifactId>
- <version>3.15.5</version>
- </dependency>
redison-spring-boot-starter依赖于与最新版本的spring-boot兼容的redison-spring数据模块。降级redison弹簧数据模块(如有必要),以支持以前的spring Boot版本:
redisson-spring-data module name | Spring Boot version |
---|---|
redisson-spring-data-16 | 1.3.y |
redisson-spring-data-17 | 1.4.y |
redisson-spring-data-18 | 1.5.y |
redisson-spring-data-2x | 2.x.y |
redisson-spring-data-3x | 3.x.y |
支持Redis多种连接模式,这里以RedissonClient工具为例
- #单机模式
- #Redis url should start with redis:// or rediss:// (for SSL connection)
- my.redisson.address = redis://127.0.0.1:6379
- my.redisson.password = wtyy
- import org.redisson.Redisson;
- import org.redisson.api.RedissonClient;
- import org.redisson.config.Config;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
-
- @Configuration
- public class RedissionConfig {
-
- @Value("${my.redisson.address}")
- private String address;
-
- @Value("${my.redisson.password}")
- private String password;
-
- /**
- * 所有对Redisson的使用都是通过RedissonClient对象
- */
- @Bean(destroyMethod = "shutdown")
- public RedissonClient redissonClient(){
- // 创建配置 指定redis地址及节点信息
- Config config = new Config();
- config.useSingleServer().setAddress(address);
- //.setPassword(password);
- // 根据config创建出RedissonClient实例
- RedissonClient redissonClient = Redisson.create(config);
- return redissonClient;
- }
- }
- my.redisson.sentinel.schema=
- my.redisson.sentinel.address = redis://xxx.xx.xxx1:19601,redis://xxx.xx.xxx2:19601,redis://xxx.xx.xxx3:19601
- my.redisson.sentinel.password = N5WAXX4z9qw
- my.redisson.sentinel.master = master-test
- my.redisson.sentinel.database = 10
- import org.redisson.Redisson;
- import org.redisson.api.RedissonClient;
- import org.redisson.config.Config;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
-
- @Configuration
- public class RedissionConfig {
-
- @Value("${my.redisson.sentinel.address}")
- private String address;
-
- @Value("${my.redisson.sentinel.password}")
- private String password;
-
- @Value("${my.redisson.sentinel.master}")
- private String master;
-
- @Value("${my.redisson.sentinel.database}")
- private Integer dataBase;
-
- @Value("${my.redisson.sentinel.schema}")
- private String schema;
-
- /**
- * 所有对Redisson的使用都是通过RedissonClient对象
- */
- @Bean(destroyMethod = "shutdown")
- public RedissonClient redissonClient(){
- Config config = new Config();
- config.useSentinelServers()
- .setScanInterval(2000) // cluster state scan interval in milliseconds
- .addSentinelAddress(address.split(","))
- .setCheckSentinelsList(false)
- .setMasterName(master)
- .setPassword(password)
- .setDatabase(dataBase);
- RedissonClient redissonClient = Redisson.create(config);
- return redissonClient;
- }
- }
- Config config = new Config();
- config.useClusterServers()
- .setScanInterval(2000) // cluster state scan interval in milliseconds
- .addNodeAddress("redis://127.0.0.1:7000", "redis://127.0.0.1:7001")
- .addNodeAddress("redis://127.0.0.1:7002");
- RedissonClient redisson = Redisson.create(config);
- Config config = new Config();
- config.useMasterSlaveServers()
- .setMasterAddress("redis://127.0.0.1:6379")
- .addSlaveAddress("redis://127.0.0.1:6389", "redis://127.0.0.1:6332", "redis://127.0.0.1:6419")
- .addSlaveAddress("redis://127.0.0.1:6399");
- RedissonClient redisson = Redisson.create(config);
(1)pom:
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.1.8.RELEASE</version>
- <relativePath/>
- </parent>
-
- <dependencies>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-actuator</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
-
- <!--<dependency>-->
- <!--<groupId>org.redisson</groupId>-->
- <!--<artifactId>redisson-spring-boot-starter</artifactId>-->
- <!--<version>3.23.5</version>-->
- <!--</dependency>-->
- <dependency>
- <groupId>org.redisson</groupId>
- <artifactId>redisson</artifactId>
- <version>3.15.0</version>
- </dependency>
- </dependencies>
(2)配置文件:
- server.port = 7777
- server.servlet.context-path=/redission
-
-
- #1、单机模式
- #Redis url should start with redis:// or rediss:// (for SSL connection)
- #my.redisson.address = redis://127.0.0.1:6379
- #my.redisson.password = wtyy
-
- #2、哨兵模式
- my.redisson.sentinel.schema=
- my.redisson.sentinel.address = redis://xxx.xx.xxx1:19601,redis://xxx.xx.xxx2:19601,redis://xxx.xx.xxx3:19601
- my.redisson.sentinel.password = N5WAXX4z9qw
- my.redisson.sentinel.master = master-test
- my.redisson.sentinel.database = 10
- import org.redisson.Redisson;
- import org.redisson.api.RedissonClient;
- import org.redisson.config.Config;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
-
- @Configuration
- public class RedissionConfig {
-
- @Value("${my.redisson.sentinel.address}")
- private String address;
-
- @Value("${my.redisson.sentinel.password}")
- private String password;
-
- @Value("${my.redisson.sentinel.master}")
- private String master;
-
- @Value("${my.redisson.sentinel.database}")
- private Integer dataBase;
-
- @Value("${my.redisson.sentinel.schema}")
- private String schema;
-
- /**
- * 所有对Redisson的使用都是通过RedissonClient对象
- */
- @Bean(destroyMethod = "shutdown")
- public RedissonClient redissonClient(){
- Config config = new Config();
- config.useSentinelServers()
- .setScanInterval(2000) // cluster state scan interval in milliseconds
- .addSentinelAddress(address.split(","))
- .setCheckSentinelsList(false)
- .setMasterName(master)
- .setPassword(password)
- .setDatabase(dataBase);
- RedissonClient redissonClient = Redisson.create(config);
- return redissonClient;
- }
- }
(3)controller接口:
- @Autowired
- private RedissonClient redissonClient;
-
- @RequestMapping("/setStr")
- public void setStr(String key,String value){
- redissonClient.getBucket(key).set(value);
- }
-
- @RequestMapping("/getStr")
- public String getStr(String key){
- return (String) redissonClient.getBucket(key).get();
- }
测试:
访问localhost:7777/redission/setStr?key=userName&value=李四
查看redis存储情况
访问localhost:7777/redission/getStr?key=userName 输出:李四
以redissonClient客户端为例,
Redisson将Redis中的字符串数据结构封装成了RBucket,通过RedissonClient的getBucket(key)方法获取一个RBucket对象实例,通过这个实例可以设置value或设置value和有效期。并且可以操作所有类型的对象。
- //1、存
- RBucket<Object> bucket = redissonClient.getBucket(你的键名称);
- //设置值,过期时间为3小时
- bucket.set(你的value,30, TimeUnit.HOURS);
-
- //2、通过key取value值
- Object name = redissonClient.getBucket(你的键名称).get();
- System.out.println(name);
- RBucket<Object> bucket = redissonClient.getBucket("myString-key");
- bucket.set("{\"userName\":\"test\",\"userPwd\":\"test\",\"email\":\"xxx@163.com\",\"captcha\":\"3552\"}");
-
-
-
- //存
- redissonClient.getBucket(key).set(value);
- //取
- String value = (String) redissonClient.getBucket(key).get();
- RList<String> list = redissonClient.getList("users");
- list.add("zs");
- list.add("ls");
- System.out.println(list);
- //通过key取value值
- List<Object> list1 = redissonClient.getList("users").get();
- //移除索引0位置元素
- list.remove(0);
- RSet<Object> set = redissonClient.getSet("users");
- set.add("zs");
- set.add("ls");
- //通过key取value值
- RSet<Object> set1 = redissonClient.getSet("users");
- RMap<Object, Object> map = redissonClient.getMap("myFirstMap");
- map.put("productId2","100055301");
-
-
- RMap<Object, Object> map = redissonClient.getMap("userMap");
- map.put("zs","张三");
- map.put("ls","李四");
- map.forEach((key,value)->{
- System.out.println("key = "+key+" ,value = "+ value);
- });
-
- //通过key取value值
- Object o = redissonClient.getMap("userMap").get("zs");
- RScoredSortedSet<String> sortedSet = redissonClient.getScoredSortedSet("sortedKey-32");
- sortedSet.add(1.0, "zs");
- sortedSet.add(2.0, "lisi");
提供了InputStream接口和OutputStream接口的实现
- //====================操作流来存储对象====================
- RBinaryStream stream = redissonClient.getBinaryStream("stream");
- stream.set("name is ".getBytes());
- OutputStream outputStream = stream.getOutputStream();
-
- outputStream.write("victory".getBytes());
- InputStream inputStream = stream.getInputStream();
-
- ByteArrayOutputStream result = new ByteArrayOutputStream();
- byte[] bytes = new byte[1024];
- int length;
- while ((length = inputStream.read(bytes)) != -1) {
- result.write(bytes, 0, length);
- }
- System.out.println(result.toString());
- RQueue<String> queue = redissonClient.getQueue("queue");
- //存值
- queue.add("zs");
- queue.add("ls");
- //取值
- String item = queue.poll();
- System.out.println(item);
-
- //
- RQueue<Object> queue1 = redissonClient.getQueue("queue");
基于Redis的分布式限流器可以用来在分布式环境下现在请求方的调用频率。既适用于不同Redisson实例下的多线程限流,也适用于相同Redisson实例下的多线程限流。该算法不保证公平性。
- RRateLimiter rateLimiter = redissonClient.getRateLimiter("rateLimiter");
- //创建限流器,最大流速:每1秒钟产生20个令牌
- rateLimiter.trySetRate(RateType.OVERALL, 20, 1, RateIntervalUnit.SECONDS);
- for (int i = 0; i < 10; i++) {
- new Thread(new Runnable() {
- int i = 0;
- @Override
- public void run() {
- while(true) {
- rateLimiter.acquire(1);
- System.out.println(Thread.currentThread() + "-" + System.currentTimeMillis() + "-" + i++);
- }
- }
- }).start();
- }
- RLock lock = redissonClient.getLock("lock");
- for (int i = 0; i < 5; i++) {
- new Thread(() -> {
- lock.lock();
- try {
- System.out.println(Thread.currentThread() + "-" + System.currentTimeMillis() + "-" + "获取了锁");
- Thread.sleep(500);
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- lock.unlock();
- }
- }).start();
- }
Redisson的分布式话题 RTopic 对象实现了发布、订阅的机制。
- //====================操作topic执行发布操作====================
- RTopic topic1 = redissonClient.getTopic("topic",new SerializationCodec());
- topic1.publish(new Message(1L,"victory",18));
-
- //====================操作topic执行订阅操作====================
- Thread.sleep(5000);
- RTopic topic = redissonClient1.getTopic("topic", new SerializationCodec());
- topic.addListener(Message.class, new MessageListener<Message>() {
- @Override
- public void onMessage(CharSequence channel, Message msg) {
- System.out.println("onMessage:=========" + channel + "; Thread:========= " + Thread.currentThread().toString());
- System.out.println(" name : " + msg.getName() + " age : " + msg.getAge());
- LoggerFactory.getLogger(RedissonDemo.class).info("Redisson接收到消息",msg);
- }
- });
- RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter("bloom-filter");
- // 初始化布隆过滤器,初始化预期插入的数据量为200,期望误差率为0.01
- bloomFilter.tryInit(200, 0.01);
- //插入数据
- bloomFilter.add("丁胜利");
- bloomFilter.add("丁向前");
- bloomFilter.add("胜利丁");
- //判断是否包含
- boolean victory = bloomFilter.contains("丁胜利");
- boolean forward = bloomFilter.contains("向前丁");
- System.out.println(victory); //true
- System.out.println(forward); //false
Redisson自定义序列化_redisson 序列化_yzh_1346983557的博客-CSDN博客
redis存取的数据一定是可序列化的,而可序列化方式可以自定义。如果不同客户端设置的可序列化方式不一样,会导致读取不一致的问题。常见的序列化方式有几下几种
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。