iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >Spring Boot使用注解集成Redis缓存的方法是什么
  • 490
分享到

Spring Boot使用注解集成Redis缓存的方法是什么

2023-06-04 05:06:13 490人浏览 泡泡鱼
摘要

这篇文章主要介绍“Spring Boot使用注解集成Redis缓存的方法是什么”,在日常操作中,相信很多人在spring Boot使用注解集成Redis缓存的方法是什么问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家

这篇文章主要介绍“Spring Boot使用注解集成Redis缓存的方法是什么”,在日常操作中,相信很多人在spring Boot使用注解集成Redis缓存的方法是什么问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Spring Boot使用注解集成Redis缓存的方法是什么”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

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;public class RedisClient {    private static Logger logger = LoggerFactory.getLogger(RedisClient.class);    private JedisConnectionFactory factory;    public RedisClient(JedisConnectionFactory factory) {        super();        this.factory = factory;    }        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;                }            });        }    }        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;            }        });    }        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);            }        });    }        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;            }        });    }        public long del(final String key) {        return redisTemplete(key, new RedisExecute<Long>() {            @Override            public Long doInvoker(Jedis jedis) {                return jedis.del(key);            }        });    }        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;    }        public Jedis getJedis() throws JedisException {        return getResource();    }        public void returnBrokenResource(Jedis jedis) {        if (jedis != null) {            jedis.close();        }    }        public void returnResource(Jedis jedis) {        if (jedis != null) {            jedis.close();        }    }        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;    }        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();    }        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;@Configurationpublic 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.javapackage 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;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里

@Autowiredprivate RedisTemplate<String, Object> redisTemplate;@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 了。

atoop/article/details/71275331

一、创建 Caching 配置类

RedisKeys.java

package com.shanhy.example.redis;import java.util.HashMap;import java.util.Map;import javax.annotation.PostConstruct;import org.springframework.stereotype.Component;@Componentpublic class RedisKeys {    // 测试 begin    public static final String _CACHE_TEST = "_cache_test";// 缓存key    public static final Long _CACHE_TEST_SECOND = 20L;// 缓存时间    // 测试 end    // 根据key设定具体的缓存时间    private Map<String, Long> expiresMap = null;    @PostConstruct    public void init(){        expiresMap = new HashMap<>();        expiresMap.put(_CACHE_TEST, _CACHE_TEST_SECOND);    }    public Map<String, Long> getExpiresMap(){        return this.expiresMap;    }}

CachingConfig.java

package com.shanhy.example.redis;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.List;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.cache.interceptor.SimpleKeyGenerator;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.redis.cache.RedisCacheManager;import org.springframework.data.redis.core.RedisTemplate;@Configuration@EnableCachingpublic class CachingConfig extends CachingConfigurerSupport {        @Override    public KeyGenerator keyGenerator() {        return new SimpleKeyGenerator() {                        @Override            public Object generate(Object target, Method method, Object... params) {                StringBuilder sb = new StringBuilder();                sb.append(target.getClass().getName());                sb.append(".").append(method.getName());                StringBuilder paramsSb = new StringBuilder();                for (Object param : params) {                    // 如果不指定,默认生成包含到键值中                    if (param != null) {                        paramsSb.append(param.toString());                    }                }                if (paramsSb.length() > 0) {                    sb.append("_").append(paramsSb);                }                return sb.toString();            }        };    }        @Bean    public CacheManager cacheManager(RedisTemplate<String, Object> redisTemplate, RedisKeys redisKeys) {        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);        // 设置缓存默认过期时间(全局的)        rcm.setDefaultExpiration(1800);// 30分钟        // 根据key设定具体的缓存时间,key统一放在常量类RedisKeys中        rcm.setExpires(redisKeys.getExpiresMap());        List<String> cacheNames = new ArrayList<String>(redisKeys.getExpiresMap().keySet());        rcm.setCacheNames(cacheNames);        return rcm;    }}

二、创建需要缓存数据的类

TestService.java

package com.shanhy.example.service;import org.apache.commons.lang3.RandomStringUtils;import org.springframework.cache.annotation.Cacheable;import org.springframework.stereotype.Service;import com.shanhy.example.redis.RedisKeys;@Servicepublic class TestService {        @Cacheable(value = RedisKeys._CACHE_TEST, key = "'" + RedisKeys._CACHE_TEST + "'")    public String testCache() {        return RandomStringUtils.randomNumeric(4);    }        @Cacheable(value = RedisKeys._CACHE_TEST)    public String testCache2(String str1, String str2) {        return RandomStringUtils.randomNumeric(4);    }}

说明一下,其中 @Cacheable 中的 value 值是在 CachingConfig的cacheManager 中配置的,那里是为了配置我们的缓存有效时间。其中 methodKeyGenerator 为 CachingConfig 中声明的 KeyGenerator。
另外,Cache 相关的注解还有几个,大家可以了解下,不过我们常用的就是 @Cacheable,一般情况也可以满足我们的大部分需求了。还有 @Cacheable 也可以配置表达式根据我们传递的参数值判断是否需要缓存。
注: TestService 中 testCache 中的 mapper.get 大家不用关心,这里面我只是访问了一下数据库而已,你只需要在这里做自己的业务代码即可。

三、测试方法

下面代码,随便放一个 Controller 中

package com.shanhy.example.controller;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.connection.jedis.RedisClient;import org.springframework.WEB.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import com.shanhy.example.service.TestService;@RestController@RequestMapping("/test")public class TestController {    private static final Logger LOG = LoggerFactory.getLogger(TestController.class);    @Autowired    private RedisClient redisClient;    @Autowired    private TestService testService;    @GetMapping("/redisCache")    public String redisCache() {        redisClient.set("shanhy", "hello,shanhy", 100);        LOG.info("getRedisValue = {}", redisClient.get("shanhy"));        testService.testCache2("aaa", "bbb");        return testService.testCache();    }}

到此,关于“Spring Boot使用注解集成Redis缓存的方法是什么”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注编程网网站,小编会继续努力为大家带来更多实用的文章!

--结束END--

本文标题: Spring Boot使用注解集成Redis缓存的方法是什么

本文链接: https://www.lsjlt.com/news/236597.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作