1. 引入依赖

在pom.xml文件中引入以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>
  1. 配置Redis连接

在application.properties文件中添加Redis连接配置:

spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.database=0
spring.redis.password=
  1. 编写Redis配置类

创建Redis配置类RedisConfig.java,注入Redis连接池和RedisTemplate:

@Configuration
public class RedisConfig {

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.database}")
    private int database;

    @Bean
    public JedisPool jedisPool() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(100);
        config.setMaxIdle(50);
        config.setMinIdle(20);
        config.setMaxWaitMillis(5000);
        return new JedisPool(config, host, port, 5000, password, database);
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(jedisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new JdkSerializationRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new JdkSerializationRedisSerializer());
        return template;
    }

    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(host);
        factory.setPort(port);
        factory.setPassword(password);
        factory.setDatabase(database);
        factory.setUsePool(true);
        return factory;
    }
}
  1. 测试Redis连接

在测试类中注入RedisTemplate,测试Redis连接是否成功:

@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Test
    public void testRedis() {
        redisTemplate.opsForValue().set("test", "Hello Redis!");
        String value = (String) redisTemplate.opsForValue().get("test");
        Assert.assertEquals("Hello Redis!", value);
    }
}
  1. 测试结果

运行测试类,如果测试通过,则表示Redis连接成功,可以开始使用Redis存储数据

SpringBoot154+Redis 181 + jedis实现配置

原文地址: https://www.cveoy.top/t/topic/eHiM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录