Redis 基础使用 及 队列、订阅

Redis介绍

  Redis是一个开源,先进的key-value存储,并用于构建高性能,可扩展的Web应用程序的完美解决方案。

  Redis从它的许多竞争继承来的三个主要特点:

  • Redis数据库完全在内存中,使用磁盘仅用于持久性。

  • 相比许多键值数据存储,Redis拥有一套较为丰富的数据类型。

  • Redis可以将数据复制到任意数量的从服务器。

Redis 优势

  • 异常快速:Redis的速度非常快,每秒能执行约11万集合,每秒约81000+条记录。

  • 支持丰富的数据类型:Redis支持最大多数开发人员已经知道像列表,集合,有序集合,散列数据类型。这使得它非常容易解决各种各样的问题,因为我们知道哪些问题是可以处理通过它的数据类型更好。

  • 操作都是原子性:所有Redis操作是原子的,这保证了如果两个客户端同时访问的Redis服务器将获得更新后的值。

  • 多功能实用工具:Redis是一个多实用的工具,可以在多个用例如缓存,消息,队列使用(Redis原生支持发布/订阅),任何短暂的数据,应用程序,如Web应用程序会话,网页命中计数等。

下载windows版本的Redis

去官网找了很久,发现原来在官网上可以下载的windows版本的,现在官网以及没有下载地址,只能在github上下载,官网只提供linux版本的下载

官网下载地址:http://redis.io/download

  github下载地址:https://github.com/MSOpenTech/redis/tags

          https://github.com/MicrosoftArchive/redis/releases

.  这里下载的是Redis-x64-3.2.100版本,我的电脑是win7 64位,所以下载64位版本的,在运行中输入cmd,然后把目录指向解压的Redis目录。

  双击redis-server.exe 启动redis。

Redistemplate 配置

  <bean id="sessionJedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
      <property name="maxTotal" value="${sessionRedis.pool.maxTotal}" />
      <property name="maxWaitMillis" value="${sessionRedis.pool.maxWaitMillis}" />
      <property name="maxIdle" value="${sessionRedis.pool.maxIdle}" />
      <property name="testOnBorrow" value="${sessionRedis.pool.testOnBorrow}" />
  </bean>

  <bean id="sessionJedisConnectionFactory"
      class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
      <property name="hostName" value="${sessionRedis.ip}" />
      <property name="port" value="${sessionRedis.port}" />
      <property name="database" value="${sessionRedis.db}"></property>
      <property name="poolConfig" ref="sessionJedisPoolConfig" />
  </bean>

  <bean id="sessionRedisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
      <property name="connectionFactory">
        <ref bean="sessionJedisConnectionFactory" />
      </property>
  </bean>

Redis 队列使用

  加入队列

  jedis.rpush("test", "1");
  jedis.rpush("test", "2");

  取队列

  for(int i = 0 ; i<3 ; i++){
    System.out.println("jedis-rpop"+jedis.lpop("test"));
  }

Redis 订阅使用

以springboot - redisTemplate 为例子

   application-dev.properties  配置:

1 1 # RedisProperties 2 2 # Redis数据库索引(默认为03 3 spring.redis.database=0 4 4 # Redis服务器地址 5 5 spring.redis.host=127.0.0.1 6 6 # Redis服务器连接端口 7 7 spring.redis.port=6379 8 8 # Redis服务器连接密码(默认为空) 9 9 spring.redis.password= 1010 # 连接池最大连接数(使用负值表示没有限制) 1111 spring.redis.pool.max-active=8 1212 # 连接池最大阻塞等待时间(使用负值表示没有限制) 1313 spring.redis.pool.max-wait=-1 1414 # 连接池中的最大空闲连接 1515 spring.redis.pool.max-idle=8 1616 # 连接池中的最小空闲连接 1717 spring.redis.pool.min-idle=0 1818 # 连接超时时间(毫秒) 1919 spring.redis.timeout=0 20 21 1 package com.aisino.projects.config; 22 2 23 3 import org.slf4j.Logger; 24 4 import org.slf4j.LoggerFactory; 25 5 import org.springframework.beans.factory.annotation.Value; 26 6 import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 27 7 import org.springframework.boot.context.properties.ConfigurationProperties; 28 8 import org.springframework.context.annotation.Bean; 29 9 import org.springframework.context.annotation.Configuration; 3010 import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; 3111 import org.springframework.data.redis.core.RedisTemplate; 3212 import org.springframework.data.redis.core.StringRedisTemplate; 3313 3414 import redis.clients.jedis.JedisPoolConfig; 3515 3616 3717 /** 3818 * Redis配置 3919 * @author aisino-xxy 4020 * @date 2018年2月12日 下午5:45:44 4121 */ 4222 @Configuration 4323 @EnableAutoConfiguration 4424 public class RedisConfig { 4525 4626 private Logger logger = LoggerFactory.getLogger(getClass()); 4727 4828 //获取springboot配置文件的值 (get的时候获取) 4929 @Value("${spring.redis.host}") 5030 private String host; 5131 5232 @Value("${spring.redis.password}") 5333 private String password; 5434 5535 5636 /** 5737 * @Bean 和 @ConfigurationProperties 5838 * 该功能在官方文档是没有提到的,我们可以把@ConfigurationProperties和@Bean和在一起使用。 5939 * 举个例子,我们需要用@Bean配置一个Config对象,Config对象有a,b,c成员变量需要配置, 6040 * 那么我们只要在yml或properties中定义了a=1,b=2,c=3, 6141 * 然后通过@ConfigurationProperties就能把值注入进Config对象中 6242 * @return 6343 */ 6444 @Bean 6545 @ConfigurationProperties(prefix = "spring.redis.pool") 6646 public JedisPoolConfig getRedisConfig() { 6747 JedisPoolConfig config = new JedisPoolConfig(); 6848 return config; 6949 } 7050 7151 @Bean 7252 @ConfigurationProperties(prefix = "spring.redis") 7353 public JedisConnectionFactory getConnectionFactory() { 7454 JedisConnectionFactory factory = new JedisConnectionFactory(); 7555 factory.setUsePool(true); 7656 JedisPoolConfig config = getRedisConfig(); 7757 factory.setPoolConfig(config); 7858 logger.info("JedisConnectionFactory bean init success."); 7959 return factory; 8060 } 8161 8262 8363 @Bean 8464 public RedisTemplate<?, ?> getRedisTemplate() { 8565 JedisConnectionFactory factory = getConnectionFactory(); 8666 logger.info(this.host+","+factory.getHostName()+","+factory.getDatabase()); 8767 logger.info(this.password+","+factory.getPassword()); 8868 RedisTemplate<?, ?> template = new StringRedisTemplate(getConnectionFactory()); 8969 return template; 9070 } 9171 }

   服务端:

1 1 package com.aisino.projects.task.web.redistemplate.service.impl; 2 2 3 3 import org.springframework.beans.factory.annotation.Autowired; 4 4 import org.springframework.data.redis.core.RedisTemplate; 5 5 import org.springframework.stereotype.Service; 6 6 7 7 import com.aisino.projects.task.web.redistemplate.service.RedisService; 8 8 9 9 1010 /** 1111 * RedisService实现 1212 * @author aisino-xxy 1313 * @date 2018年2月12日 下午5:03:38 1414 */ 1515 @Service 1616 public class RedisServiceImpl implements RedisService { 1717 1818 @Autowired 1919 private RedisTemplate<String,Object> redisTemplate; 2020 2121 @Override 2222 public void publishMsg() { 2323 redisTemplate.convertAndSend("redisTopic", "使用redisTopic向通道发送消息"); 2424 redisTemplate.convertAndSend("redisTopic22", "使用redisTopic22向通道发送消息"); 2525 } 2626 2727 }

客户端:

1 1 package com.aisino.projects.config; 2 2 3 3 import org.springframework.context.annotation.Bean; 4 4 import org.springframework.context.annotation.Configuration; 5 5 import org.springframework.data.redis.connection.RedisConnectionFactory; 6 6 import org.springframework.data.redis.core.StringRedisTemplate; 7 7 import org.springframework.data.redis.listener.PatternTopic; 8 8 import org.springframework.data.redis.listener.RedisMessageListenerContainer; 9 9 import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; 1010 1111 import com.aisino.projects.task.web.redistemplate.service.RedisReceiver; 1212 1313 @Configuration 1414 public class RedisSubListenerConfig { 1515 1616 //初始化监听器 1717 @Bean 1818 RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, 1919 MessageListenerAdapter listenerAdapter) { 2020 RedisMessageListenerContainer container = new RedisMessageListenerContainer(); 2121 container.setConnectionFactory(connectionFactory); 2222 container.addMessageListener(listenerAdapter, new PatternTopic("redisTopic")); 2323 container.addMessageListener(listenerAdapter, new PatternTopic("redisTopic22")); 2424 return container; 2525 } 2626 2727 2828 //利用反射来创建监听到消息之后的执行方法 2929 @Bean 3030 MessageListenerAdapter listenerAdapter(RedisReceiver redisReceiver) { 3131 return new MessageListenerAdapter(redisReceiver, "receiveMessage"); 3232 } 3333 3434 //使用默认的工厂初始化redis操作模板 3535 @Bean 3636 StringRedisTemplate template(RedisConnectionFactory connectionFactory) { 3737 return new StringRedisTemplate(connectionFactory); 3838 } 3939 } 40 41package com.aisino.projects.task.web.redistemplate.service; 42 43import org.springframework.stereotype.Service; 44 45@Service 46public class RedisReceiver { 47 48 public void receiveMessage(String message) { 49 //这里是收到通道的消息之后执行的方法 50 //System.out.println("频道: " + message.getChannel() + ";内容 :" + message.getBody()); 51 52 System.out.println("RedisReceiver监听消息: " + message); 53 } 54}

Redis 其他使用

  //是否存在

  jedis.exists("computer1");

  redis 计数器

  jedis.incr("computer");     jedis.decr("computer");

Redis 分布式锁

  SETNX key val
  当且仅当key不存在时,set一个key为val的字符串,返回1;若key存在,则什么都不做,返回0。

  expire key timeout
  为key设置一个超时时间,单位为second,超过这个时间锁会自动释放,避免死锁。

  // 获取连接

  Jedis conn  = jedisPool.getResource();

// 锁名,即key值

String lockKey = "lock:order" ;

// 超时时间60秒,上锁后超过此时间则自动释放锁

int lockExpire = 60;

if (conn.setnx(lockKey, identifier) == 1) {

conn.expire(lockKey, lockExpire);

// 返回value值,用于释放锁时间确认

retIdentifier = identifier;

return retIdentifier;

}

// 返回-1代表key没有设置超时时间,为key设置一个超时时间

if (conn.ttl(lockKey) == -1)  {

conn.expire(lockKey, lockExpire);

}

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )