springboot 集成Redis单机

1、redis服务搭建

centos7 搭建redis服务

2、接入相关

  pom文件依赖引入

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>23.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.41</version>
        </dependency>
    </dependencies>    

其中使用jedis来开发,jedis集成了redis的一些命令操作,封装了redis的java客户端。提供了连接池管理等。

  application配置文件

# Redis
spring.redis:
    host: localhost
    port: 6379
    password: root
    timeout: 1000
    jedis.pool:
      #jedis最大分配对象
      maxTotal: 1024
      #jedis最大保存idel状态对象数
      maxIdle: 200
      #jedis池没有对象返回时,最大等待时间
      maxWaitMillis: 1000
      testOnBorrow: true
      testOnReturn: true
      blockWhenExhausted: false

  jedis配置类

@Configuration
@Data
public class JedisConfig {

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

    @Bean(name = "jedis.pool")
    @Autowired
    public JedisPool jedisPool(@Qualifier("jedis.pool.config") JedisPoolConfig config,
                               @Value("${spring.redis.host}") String host,
                               @Value("${spring.redis.port}") int port,
                               @Value("${spring.redis.timeout}") int timeout,
                               @Value("${spring.redis.password}") String password) {
        logger.info("缓存服务器的地址:" + host + ":" + port);
        return new JedisPool(config, host, port, Protocol.DEFAULT_TIMEOUT, password);
    }

    @Bean(name = "jedis.pool.config")
    public JedisPoolConfig jedisPoolConfig(@Value("${spring.redis.jedis.pool.maxTotal}") int maxTotal,
                                           @Value("${spring.redis.jedis.pool.maxIdle}") int maxIdle,
                                           @Value("${spring.redis.jedis.pool.maxWaitMillis}") int maxWaitMillis,
                                           @Value("${spring.redis.jedis.pool.testOnBorrow}") boolean testOnBorrow,
                                           @Value("${spring.redis.jedis.pool.testOnReturn}") boolean testOnReturn) {

        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMaxWaitMillis(maxWaitMillis);
        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnReturn(testOnBorrow);
        return config;
    }

}

此处使用注解@Value来读取配置参数,也可以使用springboot的ConfigurationProperties注解来将配置文件转换成java对象使用,见springboot解析配置文件

  RedisClient类

@Component
public class RedisClient {

    private static final Logger logger = LoggerFactory.getLogger(RedisClient.class);

    @Autowired
    private JedisPool jedisPool;

     public Jedis getJedis() {
        return jedisPool.getResource();
    }

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return Boolean
     */
    public String set(final String key, String value) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            return jedis.set(key, String.valueOf(value));
        } catch (Exception e) {
            logger.error("[RedisClient] set e,", e);
            return "";
        } finally {
            close(jedis);
        }
    }

     /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public Optional<String> get(final String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return Optional.ofNullable(jedis.get(key));
        } catch (Exception e) {
            logger.error("[RedisClient] get exception,", e);
            return Optional.empty();
        } finally {
            close(jedis);
        }
    }
   
}

  测试:

    @Autowired
    private RedisClient redisClient;

    @Test
    public void redis() {
        System.out.println(redisConfig);

        redisClient.set("hello", "hello, redis");

        System.out.println(redisClient.get("hello"));

    }    

 

参照原码:Github

posted @ 2019-02-20 16:25  花拾夕  阅读(1516)  评论(0编辑  收藏  举报