Spring boot整合es,redis。启动项目报错的解决方案
Spring boo 整合es,redis项目启动报以下错误:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'elasticsearchTemplate' defined in class path resource
[org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfigura
tion.class]:
Unsatisfied dependency expressed through method 'elasticsearchTemplate' parameter 0;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'elasticsearchClient' defined in class path resource
[org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfiguration
.class]: Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.elasticsearch.client.transport.TransportClient]:
Factory method 'elasticsearchClient' threw exception; nested exception is
java.lang.IllegalStateException: availableProcessors is already set to [2], rejecting [2]
通过百度。网上给的解决方案都是在main方法中添加:
System.setProperty("es.set.netty.runtime.available.processors", "false")
我在main方法中加入以后,还是启动报错。
最后在github上面发现了解决方案:
/**
* @ Redis 配置类
*/
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
System.out.println("--进入redis--");
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<Object>(Object.class);
// 设置值(value)的序列化采用FastJsonRedisSerializer。
redisTemplate.setValueSerializer(fastJsonRedisSerializer);
redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
// 设置键(key)的序列化采用StringRedisSerializer。
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
public RedisConnectionFactory redisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
//设置redis服务器的host或者ip地址
redisStandaloneConfiguration.setHostName("120.0.0.1");
//设置redis的端口号
redisStandaloneConfiguration.setPort(6379);
// 设置redis的密码 没有设置可以不用
redisStandaloneConfiguration.setPassword("xxxxx");
// 获取第一个redis服务
redisStandaloneConfiguration.setDatabase(0);
JedisConnectionFactory factory = new JedisConnectionFactory(redisStandaloneConfiguration);
return factory;
}
@Bean
public JedisPoolConfig jedisPoolConfig() {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(10);
jedisPoolConfig.setMinIdle(2);
return jedisPoolConfig;
}
}
添加配置类之后,项目可以正常的启动了。