Redis 开发

添加组件

image-20181130164725496

如上图所示:
1. 选择应用,进入应用管理;
2. 点击组件管理
3. 点击新增组件,选择 redis

应用配置

image-20181130164853105

如上图所示,添加完之后进入应用配置就会看到 redis 相关的配置。

添加 redis 依赖

控制台操作完配置后,就进入代码代码,需要在代码中添加 spring redis starter 依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

编写代码

初始化 redisTemplate:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
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;

@Configuration
public class RedisConfig {

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Bean
    @ConditionalOnMissingBean
    public StringRedisTemplate redisTemplate() {
        return new StringRedisTemplate(redisConnectionFactory);
    }

}

如上所示,编写一个 config 类来创建 redisTemplate bean。

使用 redisTemplate:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisTestService implements InitializingBean {

    private Logger logger = LoggerFactory.getLogger(RedisTestService.class);

    @Autowired
    private StringRedisTemplate redisTemplate;

    public void testAdd() {
        redisTemplate.opsForValue().set("test-key", "test-value");
        logger.info("Test redis key[test-key] insert value:{}", "test-value");
    }

    public void testGet() {
        String s = redisTemplate.opsForValue().get("test-key");
        logger.info("Test redis key[test-key] get value:{}", s);
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        testAdd();
        testGet();
    }
}