使用spring的RedisTemplate操作redis队列

场景:
    1.在基于spring的web项目中使用redis,一般会在配置文件中配置Jedis连接池,连接工厂,RedisTemplate模板等,
     把这些类交给spring容器去创建对象,使用时只需注入即可.
    2.本例是将spring中用配置文件配置使用redis方式,改成用代码实现配置.可在main函数中直接使用连接池技术操作redis等

细节:
本例共计一个类包含以下部分:
    1.配置连接池参数 

/**1.配置连接池参数*/
	public static JedisPoolConfig getPoolConfig(){
		
		JedisPoolConfig jedisPoolConfig = new redis.clients.jedis.JedisPoolConfig();
		jedisPoolConfig.setMaxTotal(1024);
		jedisPoolConfig.setMaxIdle(100);
		jedisPoolConfig.setMinEvictableIdleTimeMillis(50000);
		jedisPoolConfig.setTimeBetweenEvictionRunsMillis(20000);
		jedisPoolConfig.setNumTestsPerEvictionRun(-1);
		jedisPoolConfig.setSoftMinEvictableIdleTimeMillis(10000);
		jedisPoolConfig.setMaxWaitMillis(1000);
		jedisPoolConfig.setTestOnBorrow(true);
		jedisPoolConfig.setTestWhileIdle(true);
		jedisPoolConfig.setTestOnReturn(false);
		jedisPoolConfig.setJmxEnabled(true);
		jedisPoolConfig.setJmxNamePrefix("pool");
		jedisPoolConfig.setBlockWhenExhausted(false);
		return jedisPoolConfig;
	}


    2.获取连接工厂
      使用时注意一定要加jedisConnetFactory.afterPropertiesSet();否则会无法初始化实例

/**2.获取连接工厂*/
	public static JedisConnectionFactory getConnectionFactory(JedisPoolConfig poolConfig){
		
		JedisConnectionFactory jedisConnetFactory = new JedisConnectionFactory();
		jedisConnetFactory.setPoolConfig(poolConfig);
		jedisConnetFactory.setHostName(hostName);
		jedisConnetFactory.setPort(port);
		
		/**必须执行这个函数,初始化JedisConnectionFactory*/
		jedisConnetFactory.afterPropertiesSet();
		 
		return jedisConnetFactory;
	}


    3.获取RedisTemplate实例
      使用时注意一定要加redisTemplate.afterPropertiesSet();否则会无法初始化实例.

/**3.获取RedisTemplate实例*/
	public static RedisTemplate getRedisTemplate(JedisConnectionFactory connectionFactory){
		
		RedisTemplate redisTemplate = new RedisTemplate();
		redisTemplate.setConnectionFactory(connectionFactory);
		StringRedisSerializer serializer = new StringRedisSerializer();
		redisTemplate.setDefaultSerializer(serializer);
		redisTemplate.setKeySerializer(serializer);
		redisTemplate.setValueSerializer(serializer);
		
		/**必须执行这个函数,初始化RedisTemplate*/
		redisTemplate.afterPropertiesSet();
		return redisTemplate;
	}


    4.main函数,属性变量,获取JSON数据字符串函数

package com.zbz.redis.client;

import java.util.concurrent.TimeUnit;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

/**
 *  
 * @ClassName: RedisTemplateClient
 * @date: 2018-12-26 下午6:11:33
 */
public class RedisTemplateClient {
	
	/**redis服务ip*/
	public static final String hostName = "127.0.0.1";
	/**redis服务端口*/
	public static final int port = 6379;
	/**队列名称*/
	public static final String template_Queue = "TEMPLATE_QUEUE";
	/**测试数据*/
	public static final String data = getData();
	
	public static void main(String [] args) throws InterruptedException{
		
		/**1.配置连接池参数*/
		JedisPoolConfig  poolConfig =getPoolConfig();
		/**2.获取连接工厂*/
		JedisConnectionFactory connectionFactory = getConnectionFactory(poolConfig);
		/**3.获取RedisTemplate实例*/
		RedisTemplate redisTemplate = getRedisTemplate(connectionFactory);
		
		System.out.println("测试开始......");
		System.out.println("队列写入数据:");
		System.out.println(data);
		/**获取RedisTemplate操作方式*/
		ListOperations operation = redisTemplate.opsForList();
		 
		operation.leftPush(template_Queue, data);
		System.out.println("主线程休眠10秒......");
		Thread.sleep(10000);
		Object strJson = operation.rightPop(template_Queue,10, TimeUnit.SECONDS);
		System.out.println("队列读出数据:");
		System.out.println(strJson);
		System.out.println("测试结束......");
		
	}

	/**获取JSON数据字符串*/
	public static String getData(){
		
		 String data=  "{\n" +
	            "    \"AREA_CODE\": \"0592\",\n" +
	            "    \"AREA_NUMBER\": \"350200\",\n" +
	            "    \"CITY_NAME\": \"厦门\",\n" +
	            "    \"DESCRIBE\": \"适合居住\",\n" +
	            "    \"POSTAL_CODE\": \"361000\"\n" +
	            "}";
		 return data;
	}


    
测试:
    使用命令 Llen TEMPLATE_QUEUE,在redis-cli.exe客户端观察队列变化情况.
 
     
以上,TKS.

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 Spring AMQP 和 Redis 消息队列可以实现分布式系统中的异步通信,提高系统的性能和可靠性。 首先,你需要在 Spring Boot 项目中添加 Spring AMQP 和 Redis 的依赖。在 pom.xml 文件中添加以下依赖: ```xml <dependencies> <!-- Spring AMQP --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> <!-- Redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> </dependencies> ``` 接下来,你需要配置 RabbitMQ 和 Redis 的连接信息。在 application.properties 文件中添加以下配置: ```properties # RabbitMQ spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=guest spring.rabbitmq.password=guest # Redis spring.redis.host=localhost spring.redis.port=6379 ``` 然后,你需要创建一个 RabbitMQ 的消息队列和一个 Redis 的消息队列。在 Spring Boot 项目中,你可以使用 @Bean 注解来创建这些队列。 ```java @Configuration public class QueueConfiguration { @Bean public Queue rabbitQueue() { return new Queue("rabbit.queue"); } @Bean public RedisQueue redisQueue() { return new RedisQueue("redis.queue"); } } ``` 在上面的代码中,我们创建了一个名为 "rabbit.queue" 的 RabbitMQ 队列和一个名为 "redis.queue" 的 Redis 队列。 接下来,你可以在你的代码中使用 RabbitTemplateRedisTemplate 来发送消息。下面是一个简单的例子: ```java @Service public class MessageService { @Autowired private RabbitTemplate rabbitTemplate; @Autowired private RedisTemplate<String, String> redisTemplate; public void sendMessageToRabbit(String message) { rabbitTemplate.convertAndSend("rabbit.queue", message); } public void sendMessageToRedis(String message) { redisTemplate.convertAndSend("redis.queue", message); } } ``` 在上面的代码中,我们创建了一个 MessageService 类来发送消息。我们使用 rabbitTemplate.convertAndSend 方法来发送消息到 RabbitMQ 队列使用 redisTemplate.convertAndSend 方法来发送消息到 Redis 队列。 最后,你需要在你的代码中使用 @RabbitListener 和 @RedisQueueListener 注解来接收消息。下面是一个简单的例子: ```java @Service public class MessageService { @Autowired private RabbitTemplate rabbitTemplate; @Autowired private RedisTemplate<String, String> redisTemplate; @RabbitListener(queues = "rabbit.queue") public void receiveMessageFromRabbit(String message) { System.out.println("Received message from RabbitMQ: " + message); } @RedisQueueListener(queues = "redis.queue") public void receiveMessageFromRedis(String message) { System.out.println("Received message from Redis: " + message); } } ``` 在上面的代码中,我们使用 @RabbitListener 注解来监听 RabbitMQ 队列中的消息,使用 @RedisQueueListener 注解来监听 Redis 队列中的消息。 总之,使用 Spring AMQP 和 Redis 消息队列可以方便地实现分布式系统中的异步通信。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值