Redis实战

springboot整合jedis访问Redis

jedis是类似于jdbc数据库连接的Redis客户端

POM.xml

 <!-- jedis -->
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>2.8.2</version>
    </dependency>

application.yml

spring:
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379

CacheServiceImpl

@Service
public class CacheServiceImpl implements CacheService {

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

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

    @Override
    public void setCache(String key, String value) {
        Jedis jedis = new Jedis(redisHost,redisPort);
        jedis.set(key,value);
        jedis.close();
    }

    @Override
    public String getCache(String key) {
        String value = null;
        Jedis jedis = new Jedis(redisHost,redisPort);
        value = jedis.get(key);
        jedis.close();

        return value;
    }
}

测试redis访问

@Controller
public class TestController {

    @Resource
    CacheService cacheService;

    @RequestMapping("/test")
    @ResponseBody
    public String test(){
        cacheService.setCache("test","我的第一个Redis缓存");
        System.out.println(cacheService.getCache("test"));
        return "Hello Spring boot";
    }
}

Redis连接池框架autoloadcache

POM.xml

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
    </dependency>
<!-- AutoloadCache 启动器 -->
        <dependency>
            <groupId>com.github.qiujiayu</groupId>
            <artifactId>autoload-cache-spring-boot-starter</artifactId>
            <version>6.9.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
<!-- apache 对象池 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

配置文件

spring:
  application:
    name: myshop
  aop:
    proxy-target-class: false
  redis:
    host: 127.0.0.1
    port: 6379
    #    cluster:
    #      max-redirects: 10
    #      nodes:
    #      - 192.168.176.128:7001
    #      - 192.168.176.128:7002
    #      - 192.168.176.129:7001
    #      - 192.168.176.129:7002
    #      - 192.168.176.130:7001
    #      - 192.168.176.130:7002
    lettuce:
      pool:
        maxActive: 2048
        maxIdle: 200
        maxWait: 1500ms
        minIdle: 20
    jedis:
      pool:
        maxActive: 2048
        maxIdle: 200
        maxWait: 1500ms
        minIdle: 20
autoload:
  cache:
    config:
      namespace: myshop
    enable: true
    proxy-target-class: true

Java配置类

package com.suoron.springboot.config;

import com.jarvis.cache.redis.AbstractRedisCacheManager;
import com.jarvis.cache.redis.LettuceRedisClusterCacheManager;
import com.jarvis.cache.serializer.ISerializer;
import com.jarvis.cache.serializer.JacksonJsonSerializer;
import io.lettuce.core.cluster.RedisClusterClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.jarvis.cache.ICacheManager;
import com.jarvis.cache.autoconfigure.AutoloadCacheProperties;
import com.jarvis.cache.clone.ICloner;
import com.jarvis.cache.map.MapCacheManager;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.lettuce.LettuceClusterConnection;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisConnectionUtils;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Field;

/**
 * 为了方便测试,使用Map缓存
 *
 * @author: jiayu.qiu
 */
@Configuration
public class AutoloadCacheConfiguration {

    // @Bean
    public ICacheManager mapCacheManager(AutoloadCacheProperties config, ICloner cloner) {
        return new MapCacheManager(config.getConfig(), cloner);
    }
    @Bean
    public ISerializer<Object> autoloadCacheSerializer() {
        return new JacksonJsonSerializer();
    }
    private static final Logger LOG = LoggerFactory.getLogger(AutoloadCacheConfiguration.class);

    @Bean
    public ICacheManager mapCacheManager(AutoloadCacheProperties config, ISerializer<Object> serializer,
                                         ApplicationContext applicationContext) {
        LettuceConnectionFactory connectionFactory = null;
        try {
            connectionFactory = applicationContext.getBean(LettuceConnectionFactory.class);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        if (null == connectionFactory) {
            return null;
        }

        RedisConnection redisConnection = null;
        try {
            redisConnection = connectionFactory.getConnection(); // 当Redis配置不正确时,此处会抛异常
        } catch (Throwable e) {
            LOG.error(e.getMessage(), e);
        }
        if (null != redisConnection) {
            SpringLettuceCacheManager manager = new SpringLettuceCacheManager((LettuceConnectionFactory) connectionFactory, serializer);
            LOG.debug("ICacheManager with SpringLettuceCacheManager auto-configured," + config.getConfig());
            return manager;
        }
        return null;
    }
}

管理类SpringLettuceCacheManager

package com.suoron.springboot.config;

import com.jarvis.cache.redis.AbstractRedisCacheManager;
import com.jarvis.cache.redis.IRedis;
import com.jarvis.cache.serializer.ISerializer;
import io.lettuce.core.api.async.RedisAsyncCommands;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisConnectionUtils;

import java.io.IOException;
import java.util.concurrent.ExecutionException;

/**
 * @author xuezhijian
 * @date 2018/6/19 上午11:03
 * @description
 */

public class SpringLettuceCacheManager extends AbstractRedisCacheManager {

    private LettuceConnectionFactory redisConnectionFactory;

    public SpringLettuceCacheManager(LettuceConnectionFactory redisConnectionFactory,ISerializer<Object> serializer) {
        super(serializer);
        this.redisConnectionFactory = redisConnectionFactory;
    }

    public LettuceConnectionFactory getRedisConnectionFactory() {
        return redisConnectionFactory;
    }


    @Override
    protected IRedis getRedis(String cacheKey) {
        return new LettuceConnectionClient(redisConnectionFactory);
    }

    public static class LettuceConnectionClient implements IRedis {
        private final LettuceConnectionFactory redisConnectionFactory;
        private final RedisConnection redisConnection;
        private final RedisAsyncCommands<byte[],byte[]> commands;

        public LettuceConnectionClient(LettuceConnectionFactory redisConnectionFactory) {
            this.redisConnectionFactory = redisConnectionFactory;
            this.redisConnection = RedisConnectionUtils.getConnection(redisConnectionFactory);
            this.commands = (RedisAsyncCommands) redisConnection.getNativeConnection();
        }

        @Override
        public void close() throws IOException {
            RedisConnectionUtils.releaseConnection(redisConnection, redisConnectionFactory);
        }

        @Override
        public void set(byte[] key, byte[] value) {
            commands.set(key, value);
        }

        @Override
        public void setex(byte[] key, int seconds, byte[] value) {
            commands.setex(key, seconds, value);
        }

        @Override
        public void hset(byte[] key, byte[] field, byte[] value) {
            commands.hset(key, field, value);
        }

        @Override
        public void hset(byte[] key, byte[] field, byte[] value, int seconds) {
            commands.hset(key, field, value);
            commands.expire(key, seconds);
        }

        @Override
        public byte[] get(byte[] key) {
            try {
                return commands.get(key).get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public byte[] hget(byte[] key, byte[] field) {
            try {
                return commands.hget(key, field).get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public void del(byte[] key) {
            commands.del(key);
        }

        @Override
        public void hdel(byte[] key, byte[]... fields) {
            commands.hdel(key, fields);
        }
    }

}

测试

    @Override
    @Cache(expire=600,expireExpression="null == #retVal ? 1:600",key="'SESSION_' + #args[0]",autoload=true)
    public UserSessionEntiy userLogin(String username, String password) {
        //TODO 去数据库中获取账号密码
        UserSessionEntiy userSessionEntiy = new UserSessionEntiy();
        userSessionEntiy.setUsername(username);
        userSessionEntiy.setPhone("13112345678");

        return userSessionEntiy;
    }

访问URL: http://localhost:8080/autoload-cache-ui.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 225,529评论 6 524
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 96,683评论 3 406
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 172,905评论 0 370
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 61,318评论 1 303
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 70,325评论 6 401
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 53,754评论 1 316
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 42,081评论 3 431
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 41,088评论 0 280
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 47,653评论 1 327
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 39,651评论 3 347
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 41,766评论 1 355
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 37,359评论 5 351
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 43,083评论 3 341
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 33,491评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 34,654评论 1 278
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 50,367评论 3 383
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 46,836评论 2 367

推荐阅读更多精彩内容

  • 一、redis的优势 1、redis简介 redis是速度非常快的非关系型数据库,是内存数据库,可以以key-va...
    我就是要皮阅读 533评论 3 6
  • 一、背景因项目需要,要引入redis做缓存,就在centos7下亲自安装了一遍redis,刚好趁着这个机会就来把r...
    神豪VS勇士赢阅读 393评论 0 1
  • Bone Collector Many years ago , in Teddy’s hometown there...
    DongBold阅读 228评论 0 0
  • 管住嘴,迈开腿 一方面,从健康的层面说来,管住嘴,健康饮食为你提供健康的身体;迈开腿,积极锻炼为你创造无尽的动力。...
    chardson阅读 156评论 0 1
  • 前天串亲戚,发现亲戚家养了两只雪白的兔子,毛发光泽亮丽,漂亮而活力十足。 我想起了小时候唯一一次与兔子产生交集的故...
    KPAX阅读 282评论 0 0