1.pom.xml导入jar依赖
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.6.2.RELEASE</version> </dependency>
2.连接redisimport com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisPassword; import org.springframework.data.redis.connection.RedisStandaloneConfiguration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import javax.annotation.PostConstruct; import java.util.HashMap; import java.util.List; import java.util.Map; @Configuration public class RedisConfig { //redis地址 @Value("${distdb.redis.host}") private String host; //redis端口号 @Value("${distdb.redis.port}") private int port; //redis密码 @Value("${distdb.redis.password}") private String password; //默认数据库 private int defaultDB; //多个数据库集合 @Value("#{'${distdb.redis.dbs}'.split(',')}") private List<Integer> dbList; //RedisTemplate实例 private static Map<Integer, RedisTemplate<String, Object>> redisTemplateMap = new HashMap<>(); /** * 初始化连接池 */ @PostConstruct public void initRedisTemplate() { defaultDB = dbList.get(0);//设置默认数据库 for (Integer db : dbList) { //存储多个RedisTemplate实例 redisTemplateMap.put(db, redisTemplate(db)); } } public LettuceConnectionFactory redisConnection(int db) { RedisStandaloneConfiguration server = new RedisStandaloneConfiguration(); server.setHostName(host); // 指定地址 server.setDatabase(db); // 指定数据库 server.setPort(port); //指定端口 server.setPassword(RedisPassword.of(password)); //指定密码 LettuceConnectionFactory factory = new LettuceConnectionFactory(server); factory.afterPropertiesSet(); //刷新配置 return factory; } //RedisTemplate模板 public RedisTemplate<String, Object> redisTemplate(int db) { //为了开发方便,一般直接使用<String,Object> RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnection(db)); //设置连接 //Json序列化配置 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); //String的序列化 StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); //key采用String的序列化方式 template.setKeySerializer(stringRedisSerializer); //hash的key采用String的序列化方式 template.setHashKeySerializer(stringRedisSerializer); //value序列化方式采用jackson template.setValueSerializer(stringRedisSerializer); //hash序列化方式采用jackson template.setHashValueSerializer(stringRedisSerializer); template.afterPropertiesSet(); return template; } /** * 指定数据库进行切换 * @param db 数据库索引 * @return */ public RedisTemplate<String, Object> getRedisTemplateByDb(int db) { return redisTemplateMap.get(db); } /** * 使用默认数据库 * * @return */ public RedisTemplate<String, Object> getRedisTemplate() { return redisTemplateMap.get(defaultDB); } }
3.redis消息监听
import com.ssish.saas.as.constant.RedisConstant;
import com.ssish.saas.as.message.PolicySupport;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
@Configuration
@AutoConfigureAfter({PolicySupport.class})
public class RedisPubSubConfig {
//MessageListenerAdapter 表示监听频道的订阅者,可以多个
@Bean
public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter adapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
//订阅频道,可以订阅多个
container.addMessageListener(adapter, new PatternTopic("policy_success"));
return container;
}
//表示监听一个频道
@Bean
public MessageListenerAdapter adapter(PolicySupport messageReceiver) {
//这个地方 是给messageListenerAdapter 传入一个消息接受的处理器,利用反射的方法调用“PolicySupport 的 onMessage 方法”
return new MessageListenerAdapter(messageReceiver, "onMessage");
}
4.消费者
import com.ssish.saas.as.constant.RedisConstant; import com.ssish.saas.as.schedule.databack.DatabackService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.connection.Message; import org.springframework.data.redis.connection.MessageListener; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.stereotype.Component; @Component @Slf4j public class PolicySupport implements MessageListener { @Autowired private RedisTemplate redisTemplate; @Autowired private DatabackService databackService; @Override public void onMessage(Message message, byte[] bytes) { RedisSerializer<String> redisSerializer = redisTemplate.getStringSerializer(); String policyId= redisSerializer.deserialize(message.getBody()); System.out.println("===========保单回传通道接收消息,policyId="+policyId); if(StringUtils.isNotBlank(policyId)){ policyId = policyId.replace("\"", ""); } String channel = redisSerializer.deserialize(message.getChannel()); if(RedisConstant.POLICY_SUCCESS.equals(channel)){ databackService.policyDataBackById(Integer.valueOf(policyId)); } } }
5.发布消息
redisTemplate.convertAndSend("policy_success", "123456");
订阅多个频道和监听多个频道参考https://www.cnblogs.com/liuyp-ken/p/10538658.html