Попробуйте определить bean-компонент типа 'redis.clients.jedis.JedisPool' в вашей конфигурации. ошибка при интеграции Redis Jedis - PullRequest
0 голосов
/ 26 апреля 2020

Я реализую Redis Jedis с приложением весенней загрузки. Я использую ниже зависимости и конфигурации. при этом я получаю сообщение об ошибке " Попробуйте определить bean-компонент типа 'redis.clients.jedis.JedisPool' в вашей конфигурации. "

При чтении хоста redis, порта и пароля из yml вручную, то работает нормально. Но поскольку я использую зависимость spring-boot-starter-data-redis , поэтому я не хочу читать узел redis, порт, пароль из файла yml, фактически он должен автоматически работать с @configuration и @bean , На самом деле салат Redis также просыпается с автоконфигурацией, но Redis Jedis - нет. Пожалуйста, помогите.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <exclusions>
        <exclusion>
            <groupId>io.lettuce</groupId>
            <artifactId>lettuce-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>   

и ниже мой файл конфигурации

@Configuration public class SchedulerConfiguration
{
    @Bean public LockProvider lockProvider(JedisPool jedisPool)
    {
        return new JedisLockProvider(jedisPool);
    }
}

1 Ответ

1 голос
/ 26 апреля 2020

Необходимо настроить Spring для использования Redis и использовать RedisTemplate при использовании spring-data-redis. Использование шаблона обеспечивает простую настройку и позволяет быстро настроить и использовать redis в приложениях Spring.

Вот как должна выглядеть конфигурация, если вы используете конфигурации на основе аннотаций

package test;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@ComponentScan("test") // Component Scan Base Package
public class RedisConfiguration{

    // Better if you can use a properties file and inject these values
    private String redisHost = "localhost";
    private int redisPort = 6379;

    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(redisHost);
        factory.setPort(redisPort);
        factory.setUsePool(true);
        return factory;
    }

    @Bean
    RedisTemplate< String, Object > redisTemplate() {
        final RedisTemplate< String, Object > template =  new RedisTemplate< String, Object >();
        template.setConnectionFactory( jedisConnectionFactory() );
        template.setKeySerializer( new StringRedisSerializer() );
        template.setHashValueSerializer( new GenericToStringSerializer< Object >( Object.class ) );
        template.setValueSerializer( new GenericToStringSerializer< Object >( Object.class ) );
        return template;
    }
}

А затем используйте в рамках услуги

@Service
public class RedisService {

    @Autowired
    private RedisTemplate< String, Object > template;

    // Methods to add and get objects from redis goes here
}

И, наконец, основной класс,

public class MainClassTest{

    public static void main(String... args) throws InterruptedException {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(RedisConfiguration.class);
        RedisService redisService = context.getBean(RedisService.class);
        // Use the service here
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...