从零开始搭建本身的网站十七:Springboot配置redis

在前面那篇介绍点击量的文章中提到过,咱们须要用redis来记录点击量,这样就不须要每次在点击文章以后,对数据库进行一次修改,修改redis中的缓存数据就能够,而后定时把redis中的数据写入数据库。
html

下面就让咱们来配置添加redis配置及redis工具类。java

一、添加Gradle依赖redis

compile('org.springframework.boot:spring-boot-starter-redis')

二、添加yaml配置文件
spring

jedis :
  host : 127.0.0.1
  port : 6379
  maxTotal: 100
  maxIdle: 10
  maxWaitMillis : 100000

三、配置和工具类代码部分
数据库

1)properties配置成bean缓存

@ConfigurationProperties(prefix = JedisProperties.JEDIS_PREFIX)
public class JedisProperties {

    static final String JEDIS_PREFIX = "jedis";

    private String host;

    private int port;

    private int maxTotal;

    private int maxIdle;

    private int maxWaitMillis;

    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 getMaxTotal() {
        return maxTotal;
    }

    public void setMaxTotal(int maxTotal) {
        this.maxTotal = maxTotal;
    }

    public int getMaxIdle() {
        return maxIdle;
    }

    public void setMaxIdle(int maxIdle) {
        this.maxIdle = maxIdle;
    }

    public int getMaxWaitMillis() {
        return maxWaitMillis;
    }

    public void setMaxWaitMillis(int maxWaitMillis) {
        this.maxWaitMillis = maxWaitMillis;
    }
}

2)Jedis自动配置类spring-boot

@Configuration
@EnableConfigurationProperties(JedisProperties.class)//开启属性注入,经过@autowired注入
@ConditionalOnClass(RedisClient.class)//判断这个类是否在classpath中存在
public class JedisAutoConfiguration {

    @Autowired
    private JedisProperties prop;

    @Bean(name = "jedisPool")
    public JedisPool jedisPool() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(prop.getMaxTotal());
        config.setMaxIdle(prop.getMaxIdle());
        config.setMaxWaitMillis(prop.getMaxWaitMillis());
        return new JedisPool(config, prop.getHost(), prop.getPort());
    }

    @Bean
    @ConditionalOnMissingBean(RedisClient.class)//容器中若是没有RedisClient这个类,那么自动配置这个RedisClient
    public RedisClient redisClient(@Qualifier("jedisPool") JedisPool pool) {
        RedisClient redisClient = new RedisClient();
        redisClient.setJedisPool(pool);
        return redisClient;
    }
}

3)RedisCilent工具类工具

public class RedisClient {

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

    private JedisPool jedisPool;

    /**
     * 存储String
     *
     * @param key   key
     * @param value String
     * @throws Exception e
     */
    public void setString(String key, String value) throws Exception {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.set(key, value);
        } finally {
            //返还到链接池
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 获取String
     *
     * @param key key
     * @return String
     * @throws Exception e
     */
    public String getString(String key) throws Exception {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.get(key);
        } finally {
            //返还到链接池
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 存储list
     *
     * @param key  key
     * @param list List
     * @param <T>  泛型
     * @throws Exception ex
     */
    public <T> void setList(String key, List<T> list) throws Exception {
        setObject(key, ObjectTranscoder.serialize(list));
    }

    /**
     * 存储对象
     *
     * @param key key
     * @param o   对象
     */
    private void setObject(String key, byte[] o) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.set(key.getBytes(), o);
        } finally {
            //返还到链接池
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 获取list
     *
     * @param key key
     * @return List
     */
    public <T> List<T> getList(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            byte[] in = jedis.get(key.getBytes());
            List<T> list = (List<T>) ObjectTranscoder.deserialize(in);
            return list;
        } finally {
            //返还到链接池
            assert jedis != null;
            jedis.close();
        }
    }

    /**
     * 存储map
     *
     * @param key key
     * @param map Map
     * @param <T> 泛型
     * @throws Exception Exception
     */
    public <T> void setMap(String key, Map<String, T> map) throws Exception {
        setObject(key, ObjectTranscoder.serialize(map));
    }

    /**
     * 获取map
     *
     * @param key key
     * @return Map
     */
    public <T> Map<String, T> getMap(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            byte[] in = jedis.get(key.getBytes());
            Map<String, T> map = (Map<String, T>) ObjectTranscoder.deserialize(in);
            return map;
        } finally {
            //返还到链接池
            assert jedis != null;
            jedis.close();
        }
    }

    public JedisPool getJedisPool() {
        return jedisPool;
    }

    public void setJedisPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }
}

4)序列化工具类this

public class ObjectTranscoder {

    public static byte[] serialize(Object value) {
        if (value == null) {
            throw new NullPointerException("Can't serialize null");
        }
        byte[] rv = null;
        ByteArrayOutputStream bos = null;
        ObjectOutputStream os = null;
        try {
            bos = new ByteArrayOutputStream();
            os = new ObjectOutputStream(bos);
            os.writeObject(value);
            os.close();
            bos.close();
            rv = bos.toByteArray();
        } catch (IOException e) {
            throw new IllegalArgumentException("Non-serializable object", e);
        } finally {
            try {
                if (os != null) os.close();
                if (bos != null) bos.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return rv;
    }

    public static Object deserialize(byte[] in) {
        Object rv = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream is = null;
        try {
            if (in != null) {
                bis = new ByteArrayInputStream(in);
                is = new ObjectInputStream(bis);
                rv = is.readObject();
                is.close();
                bis.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) is.close();
                if (bis != null) bis.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return rv;
    }
}

​四、使用
spa

@Autowired
private RedisClient redisClient;

//用其中的方法便可
redisClient.getList("");//等

这样子,咱们就能够用redis了~

同窗们去试试吧



欢迎转载,转载请注明出处 http://www.dingyinwu.com/article/57.html 

若是文章中有任何问题或者能够改进的地方,请你们多提提意见,我会很是感激。