网络上有很多教程但是很少有说springboot 版本,版本号的不同,会导致java程序无法访问虚拟机上的redis
我也是遇到了很多的坑,这里讲解的是springboot2.0.0版本的连接
首先的pom文件
redis这个是主要的,后面的pool2是有可能在2.0.0以上的版本报连接错误时用的,我自己这次没有使用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--spring2.0集成redis所需common-pool2-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.2</version>
</dependency>
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.8</version>
</dependency>
然后是redis的配置文件
spring.redis.database=1
spring.redis.host=192.168.110.128
spring.redis.port=6379
spring.redis.password=
spring.redis.timeout=5000ms
最后的配置类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import java.util.concurrent.CountDownLatch;
/**
-
@Auther: ${WM}
-
@Date: 2019/1/25 11:03
-
@Description:
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) {RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new PatternTopic(“chat”));
return container;
}@Bean
MessageListenerAdapter listenerAdapter(Receiver receiver) {
return new MessageListenerAdapter(receiver, “receiveMessage”);
}@Bean
Receiver receiver(CountDownLatch latch) {
return new Receiver(latch);
}@Bean
CountDownLatch latch() {
return new CountDownLatch(1);
}@Bean
StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
return new StringRedisTemplate(connectionFactory);
}public class Receiver {
private CountDownLatch latch;
@Autowired
public Receiver(CountDownLatch latch) {
this.latch = latch;
}public void receiveMessage(String message) {
latch.countDown();
}
}
}
这样就完成了