您好,欢迎访问一九零五行业门户网

SpringBoot如何集成redis

推荐(免费):redis教程
今天,日月在这里教大家如何使用springboot集成redis,说实话比较简单,网上也有大把的教程。先套用一下网上的简介。
定义
remote dictionary server(redis) 是一个由salvatore sanfilippo写的key-value存储系统。
redis是一个开源的使用ansi c语言编写、遵守bsd协议、支持网络、可基于内存亦可持久化的日志型、key-value数据库,并提供多种语言的api。
它通常被称为数据结构服务器,因为值(value)可以是 字符串(string), 哈希(map), 列表(list), 集合(sets) 和 有序集合(sorted sets)等类型。
reids的优点
以下是redis的一些优点。
异常快 - redis非常快,每秒可执行大约110000次的设置(set)操作,每秒大约可执行81000次的读取/获取(get)操作。
支持丰富的数据类型 - redis支持开发人员常用的大多数数据类型,例如列表,集合,排序集和散列等等。这使得redis很容易被用来解决各种问题,因为我们知道哪些问题可以更好使用地哪些数据类型来处理解决。
操作具有原子性 - 所有redis操作都是原子操作,这确保如果两个客户端并发访问,redis服务器能接收更新的值。
多实用工具 - redis是一个多实用工具,可用于多种用例,如:缓存,消息队列(redis本地支持发布/订阅),应用程序中的任何短期数据,例如,web应用程序中的会话,网页命中计数等。
redis 安装
window 下安装
下载地址:https://github.com/msopentech/redis/releases。
redis 支持 32 位和 64 位。这个需要根据你系统平台的实际情况选择,这里我们下载 redis-x64-xxx.zip压缩包到 c 盘,解压后,将文件夹重新命名为 redis。
打开一个 cmd 窗口 使用cd命令切换目录到 c:\redis
运行 redis-server.exe redis.windows.conf
如果想方便的话,可以把 redis 的路径加到系统的环境变量里,这样就省得再输路径了,后面的那个 redis.windows.conf 可以省略,如果省略,会启用默认的。输入之后,会显示如下界面:
集成redis
我们还是延用上一章的项目:springboot集成springcloud-config实现datasource热部署
1、添加依赖
<!--集成redis--><dependency>    <groupid>org.springframework.boot</groupid>    <artifactid>spring-boot-starter-redis</artifactid>    <version>1.4.1.release</version></dependency><dependency>    <groupid>com.alibaba</groupid>    <artifactid>fastjson</artifactid>    <version>1.2.3</version></dependency><dependency>    <groupid>com.fasterxml.jackson.core</groupid>    <artifactid>jackson-databind</artifactid></dependency>
2、在配置中心里添加redis配置
spring.redis.host=127.0.0.1#redis服务器连接端口spring.redis.port=6379#redis服务器连接密码(默认为空)spring.redis.password=#连接池最大连接数(使用负值表示没有限制)spring.redis.pool.max-active=8#连接池最大阻塞等待时间(使用负值表示没有限制)spring.redis.pool.max-wait=-1#连接池中的最大空闲连接spring.redis.pool.max-idle=8#连接池中的最小空闲连接spring.redis.pool.min-idle=0#连接超时时间(毫秒)spring.redis.timeout=30000
3、配置类redisconfig
import java.lang.reflect.method;import org.springframework.beans.factory.annotation.value;import org.springframework.cache.cachemanager;import org.springframework.cache.annotation.cachingconfigurersupport;import org.springframework.cache.annotation.enablecaching;import org.springframework.cache.interceptor.keygenerator;import org.springframework.cloud.context.config.annotation.refreshscope;import org.springframework.context.annotation.bean;import org.springframework.context.annotation.configuration;import org.springframework.data.redis.cache.rediscachemanager;import org.springframework.data.redis.connection.redisconnectionfactory;import org.springframework.data.redis.connection.jedis.jedisconnectionfactory;import org.springframework.data.redis.core.redistemplate;import org.springframework.data.redis.core.stringredistemplate;import org.springframework.data.redis.serializer.jackson2jsonredisserializer;import com.fasterxml.jackson.annotation.propertyaccessor; import com.fasterxml.jackson.annotation.jsonautodetect;import com.fasterxml.jackson.databind.objectmapper;@configuration@enablecaching@refreshscopepublic class redisconfig extends cachingconfigurersupport{    @value(${spring.redis.host})    private string host;    @value(${spring.redis.port})    private int port;    @value(${spring.redis.timeout})    private int timeout;    @value(${spring.redis.password})    private string password;    @value(${spring.redis.pool.max-active})    private int maxactive;    @value(${spring.redis.pool.max-wait})    private int maxwait;    @value(${spring.redis.pool.max-idle})    private int maxidle;    @value(${spring.redis.pool.min-idle})    private int minidle;        @refreshscope    @bean    public keygenerator wiselykeygenerator(){        return new keygenerator() {            @override            public object generate(object target, method method, object... params) {                stringbuilder sb = new stringbuilder();                sb.append(target.getclass().getname());                sb.append(method.getname());                for (object obj : params) {                    sb.append(obj.tostring());                }                return sb.tostring();            }        };    }        @refreshscope    @bean    public jedisconnectionfactory redisconnectionfactory() {        jedisconnectionfactory factory = new jedisconnectionfactory();        factory.sethostname(host);        factory.setport(port);        factory.settimeout(timeout); //设置连接超时时间        factory.setpassword(password);        factory.getpoolconfig().setmaxidle(maxidle);        factory.getpoolconfig().setminidle(minidle);        factory.getpoolconfig().setmaxtotal(maxactive);        factory.getpoolconfig().setmaxwaitmillis(maxwait);        return factory;    }        @refreshscope    @bean    public cachemanager cachemanager(redistemplate redistemplate) {        rediscachemanager cachemanager = new rediscachemanager(redistemplate);        // number of seconds before expiration. defaults to unlimited (0)        cachemanager.setdefaultexpiration(10); //设置key-value超时时间        return cachemanager;    }        @refreshscope    @bean    public redistemplate<string, string> redistemplate(redisconnectionfactory factory) {        stringredistemplate template = new stringredistemplate(factory);        setserializer(template); //设置序列化工具,这样reportbean不需要实现serializable接口        template.afterpropertiesset();        return template;    }        @refreshscope    private void setserializer(stringredistemplate template) {        jackson2jsonredisserializer jackson2jsonredisserializer = new jackson2jsonredisserializer(object.class);        objectmapper om = new objectmapper();        om.setvisibility(propertyaccessor.all, jsonautodetect.visibility.any);        om.enabledefaulttyping(objectmapper.defaulttyping.non_final);        jackson2jsonredisserializer.setobjectmapper(om);        template.setvalueserializer(jackson2jsonredisserializer);    }}
4、redisutils类
import java.io.serializable;import java.util.list;import java.util.set;import java.util.concurrent.timeunit;import org.springframework.beans.factory.annotation.autowired;import org.springframework.data.redis.core.hashoperations;import org.springframework.data.redis.core.listoperations;import org.springframework.data.redis.core.redistemplate;import org.springframework.data.redis.core.setoperations;import org.springframework.data.redis.core.valueoperations;import org.springframework.data.redis.core.zsetoperations;import org.springframework.stereotype.service;@servicepublic class redisutils {    @autowired    private redistemplate redistemplate;    /**     * 写入缓存     * @param key     * @param value     * @return     */    public boolean set(final string key, object value) {        boolean result = false;        try {            valueoperations<serializable, object> operations = redistemplate.opsforvalue();            operations.set(key, value);            result = true;        } catch (exception e) {            e.printstacktrace();        }        return result;    }    /**     * 写入缓存设置时效时间     * @param key     * @param value     * @return     */    public boolean set(final string key, object value, long expiretime ,timeunit timeunit) {        boolean result = false;        try {            valueoperations<serializable, object> operations = redistemplate.opsforvalue();            operations.set(key, value);            redistemplate.expire(key, expiretime, timeunit);            result = true;        } catch (exception e) {            e.printstacktrace();        }        return result;    }    /**     * 批量删除对应的value     * @param keys     */    public void remove(final string... keys) {        for (string key : keys) {            remove(key);        }    }    /**     * 批量删除key     * @param pattern     */    public void removepattern(final string pattern) {        set<serializable> keys = redistemplate.keys(pattern);        if (keys.size() > 0){            redistemplate.delete(keys);        }    }    /**     * 删除对应的value     * @param key     */    public void remove(final string key) {        if (exists(key)) {            redistemplate.delete(key);        }    }    /**     * 判断缓存中是否有对应的value     * @param key     * @return     */    public boolean exists(final string key) {        return redistemplate.haskey(key);    }    /**     * 读取缓存     * @param key     * @return     */    public object get(final string key) {        object result = null;        valueoperations<serializable, object> operations = redistemplate.opsforvalue();        result = operations.get(key);        return result;    }    /**     * 哈希 添加     * @param key     * @param hashkey     * @param value     */    public void hmset(string key, object hashkey, object value){        hashoperations<string, object, object> hash = redistemplate.opsforhash();        hash.put(key,hashkey,value);    }    /**     * 哈希获取数据     * @param key     * @param hashkey     * @return     */    public object hmget(string key, object hashkey){        hashoperations<string, object, object>  hash = redistemplate.opsforhash();        return hash.get(key,hashkey);    }    /**     * 列表添加     * @param k     * @param v     */    public void lpush(string k,object v){        listoperations<string, object> list = redistemplate.opsforlist();        list.rightpush(k,v);    }    /**     * 列表获取     * @param k     * @param l     * @param l1     * @return     */    public list<object> lrange(string k, long l, long l1){        listoperations<string, object> list = redistemplate.opsforlist();        return list.range(k,l,l1);    }    /**     * 集合添加     * @param key     * @param value     */    public void add(string key,object value){        setoperations<string, object> set = redistemplate.opsforset();        set.add(key,value);    }    /**     * 集合获取     * @param key     * @return     */    public set<object> setmembers(string key){        setoperations<string, object> set = redistemplate.opsforset();        return set.members(key);    }    /**     * 有序集合添加     * @param key     * @param value     * @param scoure     */    public void zadd(string key,object value,double scoure){        zsetoperations<string, object> zset = redistemplate.opsforzset();        zset.add(key,value,scoure);    }    /**     * 有序集合获取     * @param key     * @param scoure     * @param scoure1     * @return     */    public set<object> rangebyscore(string key,double scoure,double scoure1){        zsetoperations<string, object> zset = redistemplate.opsforzset();        return zset.rangebyscore(key, scoure, scoure1);    }
5、测试,修改controller
import java.util.concurrent.timeunit;import org.slf4j.logger;import org.slf4j.loggerfactory;import org.springframework.beans.factory.annotation.autowired;import org.springframework.web.bind.annotation.pathvariable;import org.springframework.web.bind.annotation.requestmapping;import org.springframework.web.bind.annotation.restcontroller;import com.chenqi.springboot.redis.redisutils;import com.chenqi.springboot.service.testservice;@restcontrollerpublic class springbootcontroller {        public static final logger log = loggerfactory.getlogger(springbootcontroller.class);        @autowired    testservice testservice;        @autowired    private redisutils redisutils;    @requestmapping(value = /hello/{id})    public string hello(@pathvariable(value = id) string id){        //查询缓存中是否存在        boolean haskey = redisutils.exists(id);        string str = ;        if(haskey){            //获取缓存            object object =  redisutils.get(id);            log.info(从缓存获取的数据+ object);            str = object.tostring();        }else{            //从数据库中获取信息            log.info(从数据库中获取数据);            str = testservice.test();            //数据插入缓存(set中的参数含义:key值,user对象,缓存存在时间10(long类型),时间单位)            redisutils.set(id,str,10l,timeunit.minutes);            log.info(数据插入缓存 + str);        }        return str;    }}
启动项目,第一次访问:http://localhost:8002/hello/111
通过控制台输出,我们可以看到是从数据库中获取的数据,并且存入了redis缓存中。
我们再次刷新浏览器
可以看到,第二次是从缓存中读取的,我们试试不断刷新浏览器
可以看到,之后都是从缓存中获取的。
到此我们的redis就配置好了。
springboot集成redis-demo下载
急需demo的兄弟就自行下载吧,不急可以留言邮箱,一般48小时内会发。
更多相关学习敬请关注redis栏目!
以上就是springboot如何集成redis的详细内容。
其它类似信息

推荐信息