Spring Boot Redis 集成配置

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: 版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/catoop/article/details/71275331 Spring Bo...
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/catoop/article/details/71275331

Spring Boot 熟悉后,集成一个外部扩展是一件很容易的事,集成Redis也很简单,看下面步骤配置:

一、添加pom依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
        </dependency>

二、创建 RedisClient.java

注意该类存放的package

package org.springframework.data.redis.connection.jedis;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Protocol;
import redis.clients.jedis.exceptions.JedisException;

/**
 * 工具类 RedisClient
 * 因为本类中获取JedisPool调用的是JedisConnectionFactory中protected修饰的方法fetchJedisConnector()
 * 所以该类需要与JedisConnectionFactory在同一个package中
 *
 * @author 单红宇(CSDN CATOOP)
 * @create 2017年4月9日
 */
public class RedisClient {

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

    private JedisConnectionFactory factory;

    public RedisClient(JedisConnectionFactory factory) {
        super();
        this.factory = factory;
    }

    /**
     * put操作(存储序列化对象)+ 生效时间
     * 
     * @param key
     * @param value
     * @return
     */
    public void putObject(final String key, final Object value, final int cacheSeconds) {
        if (StringUtils.isNotBlank(key)) {
            redisTemplete(key, new RedisExecute<Object>() {
                @Override
                public Object doInvoker(Jedis jedis) {
                    try {
                        jedis.setex(key.getBytes(Protocol.CHARSET), cacheSeconds, serialize(value));
                    } catch (UnsupportedEncodingException e) {
                    }

                    return null;
                }
            });
        }
    }

    /**
     * get操作(获取序列化对象)
     * 
     * @param key
     * @return
     */
    public Object getObject(final String key) {
        return redisTemplete(key, new RedisExecute<Object>() {
            @Override
            public Object doInvoker(Jedis jedis) {
                try {
                    byte[] byteKey = key.getBytes(Protocol.CHARSET);
                    byte[] byteValue = jedis.get(byteKey);
                    if (byteValue != null) {
                        return deserialize(byteValue);
                    }
                } catch (UnsupportedEncodingException e) {
                    return null;
                }
                return null;
            }
        });
    }

    /**
     * setex操作
     * 
     * @param key
     *            键
     * @param value
     *            值
     * @param cacheSeconds
     *            超时时间,0为不超时
     * @return
     */
    public String set(final String key, final String value, final int cacheSeconds) {
        return redisTemplete(key, new RedisExecute<String>() {
            @Override
            public String doInvoker(Jedis jedis) {
                if (cacheSeconds == 0) {
                    return jedis.set(key, value);
                }
                return jedis.setex(key, cacheSeconds, value);
            }
        });
    }

    /**
     * get操作
     * 
     * @param key
     *            键
     * @return 值
     */
    public String get(final String key) {
        return redisTemplete(key, new RedisExecute<String>() {
            @Override
            public String doInvoker(Jedis jedis) {
                String value = jedis.get(key);
                return StringUtils.isNotBlank(value) && !"nil".equalsIgnoreCase(value) ? value : null;
            }
        });
    }

    /**
     * del操作
     * 
     * @param key
     *            键
     * @return
     */
    public long del(final String key) {
        return redisTemplete(key, new RedisExecute<Long>() {
            @Override
            public Long doInvoker(Jedis jedis) {
                return jedis.del(key);
            }
        });
    }

    /**
     * 获取资源
     * 
     * @return
     * @throws JedisException
     */
    public Jedis getResource() throws JedisException {
        Jedis jedis = null;
        try {
            jedis = factory.fetchJedisConnector();
        } catch (JedisException e) {
            logger.error("getResource.", e);
            returnBrokenResource(jedis);
            throw e;
        }
        return jedis;
    }

    /**
     * 获取资源
     * 
     * @return
     * @throws JedisException
     */
    public Jedis getJedis() throws JedisException {
        return getResource();
    }

    /**
     * 归还资源
     * 
     * @param jedis
     * @param isBroken
     */
    public void returnBrokenResource(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }

    /**
     * 释放资源
     * 
     * @param jedis
     * @param isBroken
     */
    public void returnResource(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }

    /**
     * 操作jedis客户端模板
     * 
     * @param key
     * @param execute
     * @return
     */
    public <R> R redisTemplete(String key, RedisExecute<R> execute) {
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis == null) {
                return null;
            }

            return execute.doInvoker(jedis);
        } catch (Exception e) {
            logger.error("operator redis api fail,{}", key, e);
        } finally {
            returnResource(jedis);
        }
        return null;
    }

    /**
     * 功能简述: 对实体Bean进行序列化操作.
     * 
     * @param source
     *            待转换的实体
     * @return 转换之后的字节数组
     * @throws Exception
     */
    public static byte[] serialize(Object source) {
        ByteArrayOutputStream byteOut = null;
        ObjectOutputStream ObjOut = null;
        try {
            byteOut = new ByteArrayOutputStream();
            ObjOut = new ObjectOutputStream(byteOut);
            ObjOut.writeObject(source);
            ObjOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != ObjOut) {
                    ObjOut.close();
                }
            } catch (IOException e) {
                ObjOut = null;
            }
        }
        return byteOut.toByteArray();
    }

    /**
     * 功能简述: 将字节数组反序列化为实体Bean.
     * 
     * @param source
     *            需要进行反序列化的字节数组
     * @return 反序列化后的实体Bean
     * @throws Exception
     */
    public static Object deserialize(byte[] source) {
        ObjectInputStream ObjIn = null;
        Object retVal = null;
        try {
            ByteArrayInputStream byteIn = new ByteArrayInputStream(source);
            ObjIn = new ObjectInputStream(byteIn);
            retVal = ObjIn.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != ObjIn) {
                    ObjIn.close();
                }
            } catch (IOException e) {
                ObjIn = null;
            }
        }
        return retVal;
    }

    interface RedisExecute<T> {
        T doInvoker(Jedis jedis);
    }
}

三、创建Redis配置类

RedisConfig.java

package com.shanhy.example.redis;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.RedisClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Redis配置
 * 
 * @author 单红宇(CSDN catoop)
 * @create 2016年9月12日
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new RedisObjectSerializer());
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    public RedisClient redisClient(JedisConnectionFactory factory){
        return new RedisClient(factory);
    }
}

RedisObjectSerializer.java

package com.shanhy.example.redis;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

/**
 * 实现对象的序列化接口
 * @author   单红宇(365384722)
 * @myblog  http://blog.csdn.net/catoop/
 * @create    2017年4月9日
 */
public class RedisObjectSerializer implements RedisSerializer<Object> {

    private Converter<Object, byte[]> serializer = new SerializingConverter();
    private Converter<byte[], Object> deserializer = new DeserializingConverter();

    static final byte[] EMPTY_ARRAY = new byte[0];

    @Override
    public Object deserialize(byte[] bytes) {
        if (isEmpty(bytes)) {
            return null;
        }

        try {
            return deserializer.convert(bytes);
        } catch (Exception ex) {
            throw new SerializationException("Cannot deserialize", ex);
        }
    }

    @Override
    public byte[] serialize(Object object) {
        if (object == null) {
            return EMPTY_ARRAY;
        }

        try {
            return serializer.convert(object);
        } catch (Exception ex) {
            return EMPTY_ARRAY;
        }
    }

    private boolean isEmpty(byte[] data) {
        return (data == null || data.length == 0);
    }

}

四、创建测试方法

下面代码随便放一个Controller里

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 缓存测试
     *
     * @return
     * @author  SHANHY
     * @create  2016年9月12日
     */
    @RequestMapping("/redisTest")
    public String redisTest() {
        try {
            redisTemplate.opsForValue().set("test-key", "redis测试内容", 2, TimeUnit.SECONDS);// 缓存有效期2秒

            logger.info("从Redis中读取数据:" + redisTemplate.opsForValue().get("test-key").toString());

            TimeUnit.SECONDS.sleep(3);

            logger.info("等待3秒后尝试读取过期的数据:" + redisTemplate.opsForValue().get("test-key"));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "OK";
    }

五、配置文件配置Redis

application.yml

spring:
  # Redis配置
  redis:
    host: 192.168.1.101
    port: 6379
    password:
    # 连接超时时间(毫秒)
    timeout: 10000
    pool:
      max-idle: 20
      min-idle: 5
      max-active: 20
      max-wait: 2

这样就完成了Redis的配置,可以正常使用 redisTemplate 了。

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
相关文章
|
8天前
|
安全 Java 开发者
深入理解Spring Boot配置绑定及其实战应用
【4月更文挑战第10天】本文详细探讨了Spring Boot中配置绑定的核心概念,并结合实战示例,展示了如何在项目中有效地使用这些技术来管理和绑定配置属性。
17 1
|
6天前
|
Java 数据库连接 数据安全/隐私保护
springBoot集成token认证,最全Java面试知识点梳理
springBoot集成token认证,最全Java面试知识点梳理
|
8天前
|
NoSQL Linux Redis
在CentOS上安装和配置Redis
在CentOS上安装和配置Redis
89 0
|
8天前
|
XML Java 数据格式
Spring高手之路18——从XML配置角度理解Spring AOP
本文是全面解析面向切面编程的实践指南。通过深入讲解切面、连接点、通知等关键概念,以及通过XML配置实现Spring AOP的步骤。
24 6
Spring高手之路18——从XML配置角度理解Spring AOP
|
8天前
|
NoSQL Java MongoDB
【MongoDB 专栏】MongoDB 与 Spring Boot 的集成实践
【5月更文挑战第11天】本文介绍了如何将非关系型数据库MongoDB与Spring Boot框架集成,以实现高效灵活的数据管理。Spring Boot简化了Spring应用的构建和部署,MongoDB则以其对灵活数据结构的处理能力受到青睐。集成步骤包括:添加MongoDB依赖、配置连接信息、创建数据访问对象(DAO)以及进行数据操作。通过这种方式,开发者可以充分利用两者优势,应对各种数据需求。在实际应用中,结合微服务架构等技术,可以构建高性能、可扩展的系统。掌握MongoDB与Spring Boot集成对于提升开发效率和项目质量至关重要,未来有望在更多领域得到广泛应用。
【MongoDB 专栏】MongoDB 与 Spring Boot 的集成实践
|
8天前
|
消息中间件 JSON Java
RabbitMQ的springboot项目集成使用-01
RabbitMQ的springboot项目集成使用-01
|
8天前
|
搜索推荐 Java 数据库
springboot集成ElasticSearch的具体操作(系统全文检索)
springboot集成ElasticSearch的具体操作(系统全文检索)
|
8天前
|
消息中间件 开发框架 Java
什么是Spring Boot 自动配置?
Spring Boot 是一个流行的 Java 开发框架,它提供了许多便利的功能和工具,帮助开发者快速构建应用程序。其中一个最引人注目的特性是其强大的自动配置功能。
13 0
|
8天前
|
网络协议 Java Spring
Springboot 集成websocket
Springboot 集成websocket
14 0
|
8天前
|
安全 Java 数据库连接
在IntelliJ IDEA中通过Spring Boot集成达梦数据库:从入门到精通
在IntelliJ IDEA中通过Spring Boot集成达梦数据库:从入门到精通

热门文章

最新文章