SpringBoot整合Redis

添加pom依赖

<!--redis-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-redis</artifactId>
    <version>1.4.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

application.yml配置

spring:
  #reids配置
  redis:
    host: localhost
    port: 6379
    password: 123456
    jedis:
      pool:
        max-active: 8 #连接池最大连接数(使用负值表示没有限制)
        max-wait: -1 #连接池最大阻塞等待时间(使用负值表示没有限制)
        max-idle: 8 #连接池中的最大空闲连接
        min-idle: 0 #连接池中的最小空闲连接
    timeout: 300000 #连接超时时间(毫米)

初始化注入Jedis

package com.xxqy.shopping.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;

/**
 * 注入JedisPool
 * @Author: yww
 */
@Configuration
public class RedisConfig{

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

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

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

    @Value("${spring.redis.timeout}")
    private Integer timeout;

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

    @Value("${spring.redis.jedis.pool.max-wait}")
    private long maxWaitMillis;

    public static JedisPool jedisPool;//获取jedisPool连接池

    //初始化jedisPool
    @Bean
    public JedisPool JedisPool(){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        //连接耗尽时是否阻塞,false报异常,true阻塞直到超时,默认为true
//        jedisPoolConfig.setBlockWhenExhausted(true);
        //是否启用pool的jmx管理功能,默认为true
        JedisPool pool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
        System.out.println("JedisPool注入成功!");
        System.out.println("redis地址: "+host + ":"+port);
        System.out.println(pool);
        jedisPool = pool;
        return pool;
    }
}

编写reids工具类

package com.xxqy.shopping.utils;

import com.xxqy.shopping.config.RedisConfig;
import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * jedis3.0之前使用 jedisPool.returnResource(jedis)关闭连接
 * jedis3.0之后使用 jedis.close()关闭连接
 * redis支持类型:
 *          String(字符串),Hash(哈希),List(列表),Set(集合),Zset(sorted set:有序集合)
 * @Author: yww
 */
public class RedisUtil {

    /**
     * 初始化Jedis连接
     * @param indexDb 选择reids库 0-15
     * @return
     */
    private static Jedis getJedis(int indexDb){
        Jedis jedis =null;
        try{
            if(RedisConfig.jedisPool!=null){
                jedis = RedisConfig.jedisPool.getResource();
                jedis.select(indexDb);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return jedis;
    }


    /**
     * 通过key获取存储redis中的value
     * @param key
     * @return 成功返回value 失败返回null
     */
    public static String get(String key,int indexDb){
        Jedis jedis = null;
        String value = null;
        try{
            jedis = getJedis(indexDb);
            value = jedis.get(key);
        }finally{
            assert jedis != null;//assert断言 ,jedis为空则异常,不为空就继续进行
            jedis.close();//关闭jedis连接
        }
        return value;
    }

    /**
     * 通过key获取存储在reids中的value
     * @param key
     * @param indexDb 选择reids库 0-15
     * @return 成功返回value 失败返回null
     */
    public static byte[] get(byte[] key,int indexDb){
        Jedis jedis = null;
        byte[] value = null;
        try{
            jedis = getJedis(indexDb);
            value = jedis.get(key);
        }finally {
            assert jedis != null;
            jedis.close();
        }
        return value;
    }

    /**
     * 向redis存入key和value,并释放连接资源
     * @param key
     * @param value
     * @param indexDb 选择reids库 0-15
     * @return 成功返回OK
     */
    public static String set(String key,String value,int indexDb){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.set(key,value);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 向redis存入key和value,并释放连接资源
     * @param key
     * @param value
     * @param indexDb
     * @return 成功返回OK
     */
    public static String set(byte[] key,byte[] value,int indexDb){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.set(key,value);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 删除指定的key,也可以传入一个包含key的数组
     * @param indexDb
     * @param keys 一个key或多个
     * @return 返回删除成功的个数
     */
    public static Long del(int indexDb, String... keys){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.del(keys);
        }finally{
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 通过key向指定的value追加值
     * @param key
     * @param str
     * @param indexDb
     * @return 成功返回 追加后value的长度
     */
    public static Long append(String key,String str,int indexDb) {
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.append(key,str);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 判断key是否存在
     * @param key
     * @param indexDb redis库 0-15
     * @return true Or false
     */
    public static Boolean exists(String key,int indexDb){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.exists(key);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 清空当前数据库中所有的key,此命令从不失败
     * @param indexDb
     * @return 返回OK
     */
    public static String flushDb(int indexDb){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.flushDB();
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 以秒为单位,返回该 key 的剩余生存时间
     * @param key
     * @param indexDb
     * @return 当key不存在时,返回 -2, 当key存在但没有设置剩余生存时间时,返回 -1, 否则,以秒为单位,返回key的剩余生存时间, 异常返回 0
     */
    public static Long ttl(String key,int indexDb){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.ttl(key);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 移出该 key 的生存时间 ,将这个key 从 [易失的](带生存时间的key)转换成[持久的](一个不带生存时间,永不过期的key)
     * @param key
     * @param indexDb
     * @return
     */
    public static Long persist(String key,int indexDb){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.persist(key);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 新增key,指定过期时间(秒),如果key已存在,将会替换旧值
     * @param key
     * @param seconds 秒
     * @param value
     * @param indexDb
     * @return 设置成功返回OK,当seconds参数不合法时,返回错误
     */
    public static String setex(String key,int seconds,String value,int indexDb){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.setex(key,seconds,value);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * key不存在就设置,key存在的情况下,不操作reids内存,返回0,
     * @param key
     * @param value
     * @param indexDb
     * @return
     */
    public static Long setnx(String key,String value,int indexDb){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.setnx(key,value);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 通过批量的key获取批量的value
     * @param indexDb
     * @param keys
     * @return
     */
    public static List<String> mget(int indexDb, String... keys){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.mget(keys);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 批量设置key:value,也可以一个
     * 示例:
     *  RedisUtil.mset(new String[]{"key1","value1","key2","value2"})
     * @param indexDb
     * @param keysvalues
     * @return 成功返回OK 失败/异常 返回 null
     */
    public static String mset(int indexDb,String... keysvalues){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.mset(keysvalues);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 通过key对value进行加值+1操作,当value不是int类型时会返回错误,当key不存在则value为1
     * @param key
     * @param indexDb
     * @return
     */
    public static Long incr(String key,int indexDb){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.incr(key);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 通过key给指定的value加值,如果key不存在,则value为该值
     * @param key
     * @param number
     * @param indexDb
     * @return
     */
    public static Long incrBy(String key,Long number,int indexDb){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.incrBy(key,number);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 对key的值做减减操作,如果key不存在,则设置key为-1
     * @param key
     * @param indexDb
     * @return
     */
    public static Long decr(String key,int indexDb){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.decr(key);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 通过key减去指定的value
     * @param key
     * @param number
     * @param indexDb
     * @return
     */
    public static Long decrBy(String key,Long number,int indexDb){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.decrBy(key,number);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 通过key获取value值的长度
     * @param key
     * @param indexDb
     * @return 失败返回null
     */
    public static Long strlen(String key,int indexDb){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.strlen(key);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * hash类型:
     *  通过key给field设置指定的值,如果key不存在,则先创建
     * @param key
     * @param field
     * @param value
     * @param indexDb
     * @return 如果存在返回0,异常返回null
     */
    public static Long hset(String key,String field,String value,int indexDb){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.hset(key,field,value);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * hash类型:
     *  通过key同时设置 hash的多个field
     * @param key
     * @param hash
     * @param indexDb
     * @return 返回OK 异常返回null
     */
    public static String hmset(String key, Map<String,String> hash, int indexDb){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.hmset(key,hash);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * hash类型:
     *  通过key和field获取指定的value
     * @param key
     * @param field
     * @param indexDb
     * @return 没有返回null
     */
    public static String hget(String key,String field,int indexDb){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.hget(key,field);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * hash类型:
     *  通过key和fields获取指定的value,如果没有对应的value则返回null
     * @param key
     * @param indexDb
     * @param fields 可以是一个String,也可以是String 数组
     * @return
     */
    public static List<String> hmget(String key,int indexDb,String... fields){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.hmget(key,fields);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * hash类型:
     *  通过key给指定的field的value加上指定的值
     * @param key
     * @param field
     * @param value
     * @param indexDb
     * @return
     */
    public static Long hincrby(String key,String field,Long value,int indexDb){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.hincrBy(key,field,value);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * hash类型:
     *  通过key和filed判断是否有指定的value存在
     * @param key
     * @param field
     * @param indexDb
     * @return
     */
    public static Boolean hexists(String key,String field,int indexDb){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.hexists(key,field);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * hash类型:
     *  通过key返回field的数量
     * @param key
     * @param indexDb
     * @return
     */
    public static Long hlen(String key,int indexDb){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.hlen(key);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * hash类型:
     *  通过key删除指定的field
     * @param key
     * @param indexDb
     * @param fields 一个或多个field
     * @return
     */
    public static Long hdel(String key,int indexDb,String... fields){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.hdel(key,fields);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 通过key返回所有的field
     * @param key
     * @param indexDb
     * @return
     */
    public static Set<String> hkeys(String key,int indexDb){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.hkeys(key);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 通过key返回所有的key和value
     * @param key
     * @param indexDb
     * @return
     */
    public static List<String> hvals(String key,int indexDb){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.hvals(key);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 通过key获取所有的field和value
     * @param key
     * @param indexDb
     * @return
     */
    public static Map<String,String> hgetAll(String key,int indexDb){
        Jedis jedis = null;
        Map<String,String> res = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.hgetAll(key);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 通过key向指定的set中添加value
     * @param key
     * @param indexDb
     * @param members 可以是String,也可以是String数组
     * @return
     */
    public static Long sadd(String key,int indexDb,String... members){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.sadd(key,members);
        }finally {
            assert  jedis != null;
            jedis.close();
        }
    }

    /**
     * 通过key删除set中对应的value值
     * @param key
     * @param indexDb
     * @param members
     * @return
     */
    public static Long srem(String key,int indexDb,String... members){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.srem(key,members);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 通过key判断value是否是set中的元素
     * @param key
     * @param member
     * @param indexDb
     * @return
     */
    public static Boolean sismember(String key,String member,int indexDb){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.sismember(key,member);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 通过key获取set中所有的value
     * @param key
     * @param indexDb
     * @return
     */
    public Set<String> smembers(String key,int indexDb){
        Jedis jedis = null;
        try{
            jedis = getJedis(indexDb);
            return jedis.smembers(key);
        }finally {
            assert jedis != null;
            jedis.close();
        }
    }
}

测试使用

	@SysLog("访问登录界面")
	@RequestMapping("/login")
	public String login(){
	    //TODO redis使用
	    RedisUtil.set("name","张三",1);
	    String name = RedisUtil.get("name", 1);
	    System.out.println(name);
	    return "login";
	}

查看结果
reidsManager

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值