项目1:利用redis做消息队列发布消息
项目2:利用redis订阅项目1发布的消息
项目1(发布):
properties配置文件中redis配置:
redis.hostName=192.168.1.1
redis.port=6379
redis.timeout=15000
redis.usePool=true
redis.maxIdle=6
redis.minEvictableIdleTimeMillis=300000
redis.numTestsPerEvictionRun=3
redis.timeBetweenEvictionRunsMillis=60000
spring配置文件添加redis配置(只列出了redis相关配置):
xmlns:redis=”http://www.springframework.org/schema/redis”
http://www.springframework.org/schema/redis
http://www.springframework.org/schema/redis/spring-redis-1.0.xsd
class=’org.springframework.data.redis.connection.jedis.JedisConnectionFactory’ >
class=”org.springframework.data.redis.serializer.StringRedisSerializer” />
RedisDao接口:
import java.util.Map;
import org.springframework.data.redis.core.ValueOperations;
public interface RedisDao {
/*
* 设置频道
*/
public static final String TQCHANNEL = “channel_message”;
public void sendMessage(String channel, String message);
}
RedisDaoImpl实现类:
public class RedisDaoImpl implements RedisDao {
@Autowired
public RedisTemplate redisTemplate;
@Override
public void sendMessage(String channel, String message) {
System.out.println(“开始发布消息。。。”);
redisTemplate.convertAndSend(channel, message);
System.out.println(“发布成功!”);
}
}
程序中调用RedisDaoImpl发布消息:
redisDao.sendMessage(“channel_message”, “要发布的字符串”);
项目2(订阅):
properties配置文件中redis配置:
redis.hostName=192.168.1.1
redis.port=6379
redis.timeout=15000
redis.usePool=true
redis.maxIdle=6
redis.minEvictableIdleTimeMillis=300000
redis.numTestsPerEvictionRun=3
redis.timeBetweenEvictionRunsMillis=60000
spring配置文件添加redis配置(只列出了redis相关配置):
xmlns:redis=”http://www.springframework.org/schema/redis”
http://www.springframework.org/schema/redis
http://www.springframework.org/schema/redis/spring-redis-1.0.xsd
id=’jedisConnectionFactory’
class=’org.springframework.data.redis.connection.jedis.JedisConnectionFactory’ >
class=”org.springframework.data.redis.listener.adapter.MessageListenerAdapter”>
–>
topic=”tq_message” />
监听器TQMessageDelegateListener代码:
public class TQMessageDelegateListener {
@Autowired
protected JdbcTemplate jdbcTemplate ;
@Autowired
private JdbcTemplate jdbc;
//private UserController user = new UserController();
public void handleMessage(String message){
System.out.println(“监听到的消息为:”+message);
}