spring redis消息官方入门例子

参考:http://spring.io/guides/gs/messaging-redis/


非常典型而简单的一个Message-Driven风格.

1.主要依赖pom.xml

<dependency>
	<groupId>redis.clients</groupId>
	<artifactId>jedis</artifactId>
	<version>2.5.2</version>
</dependency>
<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-pool2</artifactId>
	<version>2.2</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-webmvc</artifactId>
	<version>${spring.version}</version>
</dependency>
<dependency>
	<groupId>org.springframework.data</groupId>
	<artifactId>spring-data-redis</artifactId>
	<version>1.4.1.RELEASE</version>
</dependency>
2.Bean配置AppConfig
@Configuration
public class AppConfig {
    @Bean
    public RedisConnectionFactory redisConnectionFactory(){
        JedisConnectionFactory redisConnectionFactory=new JedisConnectionFactory();
        redisConnectionFactory.setHostName("192.168.1.118");
        redisConnectionFactory.setUsePool(true);
        return redisConnectionFactory;
    }
    @Bean
    StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
        return new StringRedisTemplate(connectionFactory);
    }
    
    @Bean
    public CountDownLatch latch() {
        return new CountDownLatch(1);
    }
    @Bean
    public Receiver receiver(CountDownLatch latch) {
        return new Receiver(latch);
    }
    @Bean
    public MessageListenerAdapter listenerAdapter(Receiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, new PatternTopic("chat"));
        return container;
    }
}

3.消息接收端Receiver

public class Receiver {
    private CountDownLatch latch;
    @Autowired
    public Receiver(CountDownLatch latch) {
        this.latch = latch;
    }
    public void receiveMessage(String message) {
        System.out.println("Received <" + message + ">");
        latch.countDown();
    }
}

4.消息发送端Main

public class Main {
    public static void main(String[] args) throws InterruptedException {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);

        StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class);
        CountDownLatch latch = ctx.getBean(CountDownLatch.class);

        System.out.println("Sending message...");
        template.convertAndSend("chat", "Hello from Redis!");

        latch.await();
        System.exit(0);

    }
}

你可能感兴趣的:(redis,spring,jedis,Message-Driven)