SpringBoot 整合redis

1、添加项目依赖

 
            redis.clients
            jedis
        
        
            org.springframework.boot
            spring-boot-starter-test
        

2、单实例连接

 //Jedis单机测试
    @Test
    public void testJedisSingle() {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.set("str", "单机测试Jedis");
        String str = jedis.get("str");
        System.out.println(str);
        jedis.close();
    }

3、使用连接池连接

 //Jedis连接池测试
    @Test
    public void testJedisPool() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        //最大连接数
        jedisPoolConfig.setMaxTotal(30);
        //最大连接空闲数
        jedisPoolConfig.setMaxIdle(2);
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, "127.0.0.1", 6379);
        Jedis resourceJedis = jedisPool.getResource();
        resourceJedis.set("str", "Jedis连接池测试");
        String str = resourceJedis.get("str");
        System.out.println(str);
        resourceJedis.close();
    }

4、编写JedisConfig 配置

package com.yy.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class JedisConfig {

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

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

    @Value("${spring.redis.jedis.pool.max-active}")
    private int maxActive;

    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;

    @Value("${spring.redis.jedis.pool.min-idle}")
    private int minIdle;

    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMinIdle(minIdle);
        jedisPoolConfig.setMaxTotal(maxActive);;
        return jedisPoolConfig;
    }

    @Bean
    public JedisPool jedisPool(JedisPoolConfig jedisPoolConfig){
        return new JedisPool(jedisPoolConfig,host,port);
    }

}

5、application.yml 配置文件

spring:
  redis:
    host: localhost
    port: 6379
    jedis:
      pool:
        max-idle: 6    #最大空闲数
        max-active: 10 #最大连接数
        min-idle: 2    #最小空闲数

 

你可能感兴趣的:(spring,boot,redis,java)