SpringBoot集成redis【Jedis】

1、pom.xml的引用

<dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <version>1.18.10</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
 </dependency>
 <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependenc>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.10.0</version>
</dependency>

這裏的lombok是爲了簡化實體類的get/set

2、application.properties

spring.redis.host=127.0.0.0
spring.redis.port=6379
spring.redis.password=
#連接超時時間
spring.redis.timeout=0
#連接的庫
spring.redis.database=15
#連接池配置
spring.redis.pool.max-total=100
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0

3、redis自動注入配置相關的信息

package com.cat.code.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 JedisConf {
    @Value("${spring.redis.host}")
    private String redisHost;
    @Value("${spring.redis.port}")
    private int redisPort;	
    @Value("${spring.redis.password}")
    private String redisPasswd;
    @Value("${spring.redis.database}")
    private int redisDb;
    @Value("${spring.redis.timeout}")
    private int redisTimeout;    
    @Value("${spring.redis.pool.max-total}")
    private int redisMaxTotal; 
    @Value("${spring.redis.pool.max-wait}")
    private int redisMaxWait;    
    @Value("${spring.redis.pool.max-idle}")
    private int redisMaxIdle;
    @Value("${spring.redis.pool.min-idle}")
    private int redisMinIdle;
    
    @Bean
    public JedisPool redisPoolFactory()  throws Exception{
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(redisMaxTotal);
        jedisPoolConfig.setMaxIdle(redisMaxIdle);
        jedisPoolConfig.setMinIdle(redisMinIdle);
        jedisPoolConfig.setMaxWaitMillis(redisMaxWait);
        jedisPoolConfig.setTestOnBorrow(true);
        jedisPoolConfig.setTestOnReturn(true);
        // 連接耗盡時是否阻塞, false報異常,ture阻塞直到超時, 默認true
//        jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
        // 是否啓用pool的jmx管理功能, 默認true
        jedisPoolConfig.setJmxEnabled(true);
        if (redisPasswd != null && redisPasswd.trim().length() == 0) {
        	redisPasswd = null;
        }
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, redisHost, redisPort, redisTimeout, redisPasswd, redisDb);
        return jedisPool;
    }
 
}

4、對jedis調用進行簡單封裝,每次重新獲取連接池資源和歸還連接池資源

package com.cat.code.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.Serializable;
import java.util.Set;

/**
 * @Description: 配置redis連接池
 */
@Component
public class RedisTemplate {

    @Autowired
    private JedisPool jedisPool;

    /**
     * key-value存儲
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key, String value) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String res = jedis.set(key, value);
            return (res == null || !res.equalsIgnoreCase("OK") ? false : true);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return false;
    }

    /**
     * key-value存儲設置過期時間
     * @param key
     * @param value
     * @param expire_time
     * @return
     */
    public boolean set(String key, String value, int expire_time) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String res = jedis.set(key, value, "NX", "EX", expire_time);
            return (res == null || !res.equalsIgnoreCase("OK") ? false : true);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return false;
    }

    /**
     * key-value存儲設置過期時間,當存在替換爲新的值
     * @param key
     * @param value
     * @param expire_time
     * @return
     */
    public boolean setex(String key, String value, int expire_time) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String res = jedis.setex(key, expire_time, value);
            return (res == null || !res.equalsIgnoreCase("OK") ? false : true);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return false;
    }

    /**
     * 獲取key-value 值
     * @param key
     * @return
     */
    public String get(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String res = jedis.get(key);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return null;
    }

    /**
     * key是否存在
     * @param key
     * @return
     */
    public boolean exist(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            Boolean res = jedis.exists(key);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return false;
    }

    /**
     * list左進隊列
     * @param key
     * @param values
     * @return
     */
    public Long lpush(String key, String... values) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            Long ret = jedis.lpush(key, values);
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return null;
    }

    /**
     * list 右進隊列
     * @param key
     * @return
     */
    public String rpop(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String value = jedis.rpop(key);
            return value;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return null;
    }

    /**
     * set key-values存儲
     * @param key
     * @param values
     * @return
     */
    public Long sadd(String key,String... values){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.sadd(key,values);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return null;
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

    /**
     * set key-value獲取
     * @param key
     * @return
     */
    public String spop(String key){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.spop(key);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return null;
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

    /**
     *命令將 key 中儲存的數字值增一
     * @param key
     * @return
     */
        public Long incr(String key){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.incr(key);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return null;
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }
}

5、User實體類,繼承Serializable序列化是非必要

package com.cat.code.po;

import lombok.Data;

import java.io.Serializable;

/**
 * @Author: lvgang
 * @Time: 2019/10/29 16:43
 * @Email: [email protected]
 * @Description: todo
 */
@Data
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    private Long id;
    private String name;
    private Integer age;

    public User(){}

    public User(Long id,String name,Integer age){
        this.id = id;
        this.name = name;
        this.age = age;
    }

}

6、調用redis存取,在大部分情況下是OK的,保證資源存取不會出現問題

package com.cat.code;

import com.cat.code.config.RedisTemplate;
import com.cat.code.po.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

/**
 * @Author: lvgang
 * @Time: 2019/10/29 17:05
 * @Email: [email protected]
 * @Description: todo
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ServiceSpringDataRedisApplication.class)
public class RedisTest {
    private Logger logger = LoggerFactory.getLogger(RedisTest.class);

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ObjectMapper objectMapper = new ObjectMapper();

    @Test
    public void test1() throws Exception{
        String key = "user1";
        String json = objectMapper.writeValueAsString(new User(1L,"admin",21));
        redisTemplate.set(key,json);
        String value = redisTemplate.get(key);
        User user = objectMapper.readValue(value,User.class);
        logger.info("user:{}",user.toString());
    }

    @Test
    public void test2(){
        ExecutorService executorService = Executors.newFixedThreadPool(1000);
        IntStream.range(0, 1000).forEach(i->{
            executorService.execute(()->{
                logger.info("i:{}",i);
                redisTemplate.incr("count");//累加
                if(i%2==1){
                    redisTemplate.sadd("set",""+i);//添加
                }else {
                    String value = redisTemplate.spop("set");//取出
                    logger.info("第i次:{}獲取{}",i,value);
                }
            });
        });
    }
}

7、寫在最後,當我們對redis連接要求不是那麼高時,我建議直接使用spring-boot-data-redis

pom.xml依賴
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.1.8.RELEASE</version>
        </dependency>

服務直接自動注入使用
@Autowired
 private StringRedisTemplate stringRedisTemplate;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章