SpringBoot整合Redis

一:配置

  1. pom.xml添加依赖
 		<!-- jedis依赖 -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.7.1</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.38</version>
        </dependency>
  1. application.properties配置redis
 		redis.host=127.0.0.1
		redis.port=6379
		redis.timeout=3
		redis.password=123456
		redis.poolMaxTotal=10
		redis.poolMaxIdle=10
		redis.poolMaxWait=3

二:代码

  1. JedisPoolFactory.java
 		
	import org.springframework.beans.factory.annotation.Autowired;
	import org.springframework.context.annotation.Bean;
	import org.springframework.stereotype.Service;
	import redis.clients.jedis.JedisPool;
	import redis.clients.jedis.JedisPoolConfig;
	
	@Service
	public class JedisPoolFactory {
	    @Autowired
	    RedisConf redisConfig;
	    @Bean
	    public JedisPool JedisPoolFactory() {
	        JedisPoolConfig poolConfig = new JedisPoolConfig();
	        poolConfig.setMaxIdle(redisConfig.getPoolMaxIdle());
	        poolConfig.setMaxTotal(redisConfig.getPoolMaxTotal());
	        poolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait() * 1000);
	        JedisPool jp = new JedisPool(poolConfig, redisConfig.getHost(), redisConfig.getPort(),
	                redisConfig.getTimeout()*1000, redisConfig.getPassword(), 0);
	        return jp;
	    }
	
	}

  1. RedisConf.java
 		
	package com.example.demo.redis;


	import org.springframework.boot.context.properties.ConfigurationProperties;
	import org.springframework.stereotype.Component;
	
	@Component
	@ConfigurationProperties(prefix="redis")
	public class RedisConf {
	    private String host;
	    private int port;
	    private int timeout;//秒
	
	    public String getHost() {
	        return host;
	    }
	
	    public void setHost(String host) {
	        this.host = host;
	    }
	
	    public int getPort() {
	        return port;
	    }
	
	    public void setPort(int port) {
	        this.port = port;
	    }
	
	    public int getTimeout() {
	        return timeout;
	    }
	
	    public void setTimeout(int timeout) {
	        this.timeout = timeout;
	    }
	
	    public String getPassword() {
	        return password;
	    }
	
	    public void setPassword(String password) {
	        this.password = password;
	    }
	
	    public int getPoolMaxTotal() {
	        return poolMaxTotal;
	    }
	
	    public void setPoolMaxTotal(int poolMaxTotal) {
	        this.poolMaxTotal = poolMaxTotal;
	    }
	
	    public int getPoolMaxIdle() {
	        return poolMaxIdle;
	    }
	
	    public void setPoolMaxIdle(int poolMaxIdle) {
	        this.poolMaxIdle = poolMaxIdle;
	    }
	
	    public int getPoolMaxWait() {
	        return poolMaxWait;
	    }
	
	    public void setPoolMaxWait(int poolMaxWait) {
	        this.poolMaxWait = poolMaxWait;
	    }
	
	    private String password;
	    private int poolMaxTotal;
	    private int poolMaxIdle;
	    private int poolMaxWait;//秒
	}
  1. RedisService.java
 		
	import com.alibaba.fastjson.JSON;
	import org.springframework.beans.factory.annotation.Autowired;
	import org.springframework.stereotype.Service;
	import redis.clients.jedis.Jedis;
	import redis.clients.jedis.JedisPool;
	
	@Service
	public class RedisService {
	    @Autowired
	    JedisPool jedisPool;
	
	    /*
	     *  获取单个对象
	     */
	    public <T> T get(String key, Class<T> clazz) {
	        Jedis jedis = null;
	        try {
	            System.out.println("start get");
	
	            jedis = jedisPool.getResource();
	            System.out.println("end get");
	
	            String str = jedis.get(key);
	            System.out.println(str);
	
	            T t = stringToBean(str, clazz);
	            return t;
	
	        } finally {
	            returnToPool(jedis);
	        }
	    }
	
	    /*
	     *  设置单个对象
	     */
	    public <T> Boolean set(KeyPrefix prefix, String key, T value) {
	        Jedis jedis = null;
	        try {
	            jedis = jedisPool.getResource();
	            String str = beanToString(value);
	            jedis.set(key, str);
	            String realKey = prefix.getPrefix() + key;
	            int expireTime = prefix.expireSeconds();
	            if (expireTime <= 0) {
	                jedis.set(realKey, str);
	            } else {
	                jedis.setex(key, expireTime, str);
	            }
	
	            return true;
	
	        } finally {
	            returnToPool(jedis);
	        }
	    }
	
	    private <T> String beanToString(T value) {
	
	        if (value == null) {
	            return null;
	        }
	        Class<?> clazz = value.getClass();
	        if (clazz == int.class || clazz == Integer.class) {
	            return "" + value;
	        } else if (clazz == long.class || clazz == Long.class) {
	            return "" + value;
	        } else if (clazz == String.class) {
	            return (String) value;
	        } else {
	            return JSON.toJSONString(value);
	        }
	    }
	
	
	    private <T> T stringToBean(String value, Class<T> clazz) {
	        if (value == null || value.length() <= 0 || clazz == null) {
	            return null;
	        }
	
	        if (clazz == int.class || clazz == Integer.class) {
	            return (T) Integer.valueOf(value);
	        } else if (clazz == long.class || clazz == Long.class) {
	            return (T) Long.valueOf(value);
	        } else if (clazz == String.class) {
	            return (T) value;
	        } else {
	            return JSON.toJavaObject(JSON.parseObject(value), clazz);
	        }
	    }
	
	
	    private void returnToPool(Jedis jedis) {
	        if (jedis != null) {
	            jedis.close();
	        }
	    }
	
	    /*
	     *  判断key是否重复
	     */
	    public <T> Boolean exists(KeyPrefix keyPrefix, String key) {
	        Jedis jedis = null;
	        try {
	            jedis = jedisPool.getResource();
	            String realKey = keyPrefix.getPrefix() + key;
	            return jedis.exists(realKey);
	        } finally {
	            returnToPool(jedis);
	
	        }
	    }
	
	    //  自增
	    public <T> Long incr(KeyPrefix keyPrefix, String key) {
	        Jedis jedis = null;
	        try {
	            jedis = jedisPool.getResource();
	            String realKey = keyPrefix.getPrefix() + key;
	            return jedis.incr(realKey);
	        } finally {
	            returnToPool(jedis);
	
	        }
	    }
	
	    //    自减
	    public <T> Long decr(KeyPrefix keyPrefix, String key) {
	        Jedis jedis = null;
	        try {
	            jedis = jedisPool.getResource();
	            String realKey = keyPrefix.getPrefix() + key;
	            return jedis.decr(realKey);
	        } finally {
	            returnToPool(jedis);
	
	        }
	
	
	    }
	}

  1. KeyPrefix.java前缀
 		
	public interface KeyPrefix {

	    public int expireSeconds();
	
	    public String getPrefix();

	}
  1. BasePrefix.java
 		
	public abstract class BasePrefix  implements KeyPrefix{
	    private int expiredTime;
	    private String prefix;
	
	    public BasePrefix(String prefix) {
	        this(0, prefix);
	        // TODO Auto-generated constructor stub
	    }
	    public BasePrefix(int expiredTime, String prefix) {
	        super();
	        this.expiredTime = expiredTime;
	        this.prefix = prefix;
	    }
	    public int expiredTime() { //默认0代表永不过期
	        return expiredTime;
	    }
	    public String getPrefix() {
	        String ClassName = getClass().getSimpleName();
	        return ClassName+":"+prefix;
	    }
	}
  1. UserKey.java
 		
	public class UserKey extends BasePrefix{

	    private UserKey(String prefix) {
	        super( prefix);
	        // TODO Auto-generated constructor stub
	    }
	
	
	    public static UserKey getById=new UserKey("id");
	    public static UserKey getByName=new UserKey("name");
	
	    @Override
	    public int expireSeconds() {
	        return 0;
	    }
	}

三:后记

谢谢大家,有问题请留言!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值