spring-boot 结合spring-data-redis使用redis的消息队列

发布消息:
 
        
1
package com.ycb.app.provider.cache;
2
3
import org.apache.commons.lang.NullArgumentException;
4
import org.springframework.beans.factory.annotation.Autowired;
5
import org.springframework.context.annotation.PropertySource;
6
import org.springframework.data.redis.core.RedisTemplate;
7
import org.springframework.data.redis.serializer.GenericToStringSerializer;
8
import org.springframework.data.redis.serializer.StringRedisSerializer;
9
import org.springframework.stereotype.Service;
10
import org.springframework.util.StringUtils;
11
12
import java.util.Set;
13
import java.util.concurrent.TimeUnit;
14
15
@Service
16
@PropertySource("classpath:bootstrap.properties") //加载配置文件
17
public class RedisService extends StringRedisSerializer {
18
19
    @Autowired
20
    private RedisTemplate<String, String> template;
21
22
    public void setKeyValue(String key, String value) {
23
        template.setValueSerializer(new GenericToStringSerializer<>(String.class));
24
        template.opsForValue().set(key, value);
25
    }
26
27
    public void setKeyValueTimeout(String key, String value, Long timeout) {
28
        template.setValueSerializer(new GenericToStringSerializer<>(String.class));
29
        template.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
30
    }
31
32
    public String getKeyValue(String key) {
33
        if (StringUtils.isEmpty(key)) {
34
            throw new NullArgumentException("key is null.");
35
        }
36
        return template.opsForValue().get(key);
37
    }
38
39
    public Set<String> getKeys(String keyPattern) {
40
        Set<String> keys = template.opsForValue().getOperations().keys(keyPattern + "*");
41
        return keys;
42
    }
43
44
    public void deleteKey(String key) {
45
        template.delete(key);
46
    }
47
48
    /**
49
     * 推入消息到redis消息通道
50
     *
51
     * @param channel
52
     * @param message
53
     */
54
    public  void publish(String channel, String message) {
55
            template.convertAndSend(channel,message);
56
    }
57
58
}
59
接收消息的普通类:
 
        
1
package com.ycb.app.provider.service;
2
3
import org.springframework.beans.factory.annotation.Autowired;
4
5
import java.util.concurrent.CountDownLatch;
6
7
public class Receiver  {
8
    private CountDownLatch latch;
9
10
    @Autowired
11
    public Receiver(CountDownLatch latch) {
12
        this.latch = latch;
13
    }
14
15
    public void receiveMessage(String message) {
16
        System.out.println("Received <" + message + ">");
17
        latch.countDown();
18
    }
19
}

springboot启动时监听消息:
1
package com.ycb.app.provider;
2
3
import com.ycb.app.provider.service.Receiver;
4
import org.springframework.boot.SpringApplication;
5
import org.springframework.boot.autoconfigure.SpringBootApplication;
6
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
7
import org.springframework.context.ApplicationContext;
8
import org.springframework.context.annotation.Bean;
9
import org.springframework.context.annotation.PropertySource;
10
import org.springframework.data.redis.connection.RedisConnectionFactory;
11
import org.springframework.data.redis.core.StringRedisTemplate;
12
import org.springframework.data.redis.listener.PatternTopic;
13
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
14
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
15
16
import java.util.concurrent.CountDownLatch;
17
18
19
@SpringBootApplication
20
@EnableDiscoveryClient
21
@PropertySource("classpath:bootstrap.properties")
22
public class AppProviderApplication {
23
24
25
    @Bean
26
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
27
                                            MessageListenerAdapter listenerAdapter) {
28
29
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
30
        container.setConnectionFactory(connectionFactory);
31
        container.addMessageListener(listenerAdapter, new PatternTopic("identifier_*"));
32
33
        return container;
34
    }
35
36
    @Bean
37
    MessageListenerAdapter listenerAdapter(Receiver receiver) {
38
        return new MessageListenerAdapter(receiver, "receiveMessage");
39
    }
40
41
    @Bean
42
    Receiver receiver(CountDownLatch latch) {
43
        return new Receiver(latch);
44
    }
45
46
    @Bean
47
    CountDownLatch latch() {
48
        return new CountDownLatch(1);
49
    }
50
51
    @Bean
52
    StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
53
        return new StringRedisTemplate(connectionFactory);
54
    }
55
56
    public static void main(String[] args) throws InterruptedException {
57
        ApplicationContext ctx = SpringApplication.run(AppProviderApplication.class, args);
58
        
59
        //监听消息
60
        StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class);
61
        CountDownLatch latch = ctx.getBean(CountDownLatch.class);
62
63
        template.convertAndSend("identifier_*", "Hello from Redis!");
64
65
        latch.await();
66
67
        //System.exit(0);
68
    }
69
}
70

controller测试方法:
 
        
1
 @RequestMapping("/redisPush")
2
    public  String redisPush(@RequestParam("userId") Long userId, @RequestParam("message")String message){
3
        redisService.publish("identifier_"+userId.toString(),message);
4
        return "success";
5
    }
redis配置:
1
# Redis数据库索引(默认为0)
2
spring.redis.database=0
3
# Redis服务器地址
4
spring.redis.host=127.0.0.1
5
# Redis服务器连接端口
6
spring.redis.port=6379
7
# Redis服务器连接密码(默认为空)
8
spring.redis.password=
9
# 连接池最大连接数(使用负值表示没有限制)
10
spring.redis.pool.max-active=8
11
# 连接池最大阻塞等待时间(使用负值表示没有限制)
12
spring.redis.pool.max-wait=-1
13
# 连接池中的最大空闲连接
14
spring.redis.pool.max-idle=8
15
# 连接池中的最小空闲连接
16
spring.redis.pool.min-idle=0
17
# 连接超时时间(毫秒)
18
spring.redis.timeout=0

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值