日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

springboot项目配置redis及其使用------R

發布時間:2024/1/18 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 springboot项目配置redis及其使用------R 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1.步驟1 :在配置文件中配置redis 的相關信息 :

## Redis 配置 ## Redis數據庫索引(默認為0) spring.redis.database=0 ## Redis服務器地址 spring.redis.host=redis地址 ## 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=3000

步驟2 : 在子項目的xx-cache中 寫redis配置類 :

package com.finance.cmp.dac.cache.config;import org.springframework.beans.factory.annotation.Value; 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.core.RedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; import redis.clients.jedis.JedisPoolConfig;/*** 緩存配置聲明** @author xiongyu*/@Configuration public class RedisConfig {@Value("${spring.redis.host}")private String host;@Value("${spring.redis.port}")private int port;@Value("${spring.redis.password}")private String password;@Value("${spring.redis.database}")private int database;@Value("${spring.redis.timeout}")private int timeout;@Value("${spring.redis.pool.max-active}")private int maxActive;@Value("${spring.redis.pool.max-idle}")private int maxIdle;@Value("${spring.redis.pool.min-idle}")private int minIdle;@Value("${spring.redis.pool.max-wait}")private long maxWait;@Beanpublic JedisConnectionFactory jedisConnectionFactory() {JedisConnectionFactory factory = new JedisConnectionFactory();factory.setHostName(host);factory.setPort(port);factory.setPassword(password);factory.setDatabase(database);factory.setTimeout(timeout);JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();jedisPoolConfig.setMaxTotal(maxActive);jedisPoolConfig.setMaxIdle(maxIdle);jedisPoolConfig.setMinIdle(minIdle);jedisPoolConfig.setMaxWaitMillis(maxWait);factory.setPoolConfig(jedisPoolConfig);return factory;}@Beanpublic RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory factory) {RedisTemplate<String, Object> template = new RedisTemplate();template.setConnectionFactory(jedisConnectionFactory());template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(new RedisObjectSerializer());return template;} } package com.finance.rst.map.engine.backend.cache.config;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 xiongyu*/ 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];@Overridepublic Object deserialize(byte[] bytes) {if (isEmpty(bytes)) {return null;}try {return deserializer.convert(bytes);} catch (Exception ex) {throw new SerializationException("Cannot deserialize", ex);}}@Overridepublic 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);} }

步驟3 : 在子項目service層 的common : 常用方法

package com.finance.cmp.dac.service.common;import java.util.Collection; import java.util.concurrent.TimeUnit;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service;import com.finance.cmp.dac.service.util.SerializeUtil;@Service public class RedisCacheService {@AutowiredRedisTemplate<String, Object> stringRedisTemplate;/* ----------- common --------- */public Collection<String> keys(String pattern) {return stringRedisTemplate.keys(pattern);}public void delete(String key) {stringRedisTemplate.delete(key);}public void delete(Collection<String> key) {stringRedisTemplate.delete(key);}public boolean hasKey(String key) {return stringRedisTemplate.hasKey(key);}/*** get* @param key* @return*/public Object get(String key) {Object value = stringRedisTemplate.opsForValue().get(key);if(value!=null) {byte[] val=(byte[]) value;value=SerializeUtil.unserialize(val);}return value;}/*** * @param key* @param obj*/public void set(String key, Object obj) {if (obj == null) {return;}stringRedisTemplate.opsForValue().set(key, SerializeUtil.serialize(obj));}/*** getString* @param key* @return*/public String getString(String key){Object value = stringRedisTemplate.opsForValue().get( key);String valueRetun = "";if(value!=null) {byte[] val=(byte[]) value;valueRetun=SerializeUtil.unserialize(val).toString();}return valueRetun;}/*** getString* @param key* @return*/public String getStringNoPrefix(String key){Object value = stringRedisTemplate.opsForValue().get(key);String valueRetun = "";if(value!=null) {byte[] val=(byte[]) value;valueRetun=SerializeUtil.unserialize(val).toString();}return valueRetun;}/*** set key time * @param key 鍵* @param obj 值* @param timeout 超時時間* @param unit 超時時間單位 參照TimeUnit*/public void setKeyByTime(String key, Object obj, Long timeout, TimeUnit unit) {if (obj == null) {return;}if (timeout != null) {stringRedisTemplate.opsForValue().set( key, SerializeUtil.serialize(obj), timeout, unit);} else {stringRedisTemplate.opsForValue().set(key, SerializeUtil.serialize(obj));}} }

序列化/反序列化類 :

package com.finance.cmp.ruleEngine.service.util;import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream;public class SerializeUtil {public static byte[] serialize(Object object) {if (object == null) {return null;}ByteArrayOutputStream bos = null;ObjectOutputStream oos = null;try {bos = new ByteArrayOutputStream();oos = new ObjectOutputStream(bos);oos.writeObject(object);byte[] bytes = bos.toByteArray();// set(key.getBytes(), str);return bytes;} catch (Exception e) {e.printStackTrace();} finally {//關閉輸出流closeOS(oos, bos);}return null;}public static Object unserialize(byte[] bytes) {if (bytes == null) {return null;}ByteArrayInputStream bis = null;ObjectInputStream ois = null;Object obj = null;try {bis = new ByteArrayInputStream(bytes);ois = new ObjectInputStream(new BufferedInputStream(bis));obj = ois.readObject();} catch (Exception e) {e.printStackTrace();} finally {//關閉輸入流closeIS(ois, bis);}return obj;}/**關閉輸出流*/private static void closeOS(ObjectOutputStream oos, ByteArrayOutputStream bos) {try {oos.close();bos.close();} catch (IOException e) {e.printStackTrace();}}/**關閉輸入流*/private static void closeIS(ObjectInputStream ois, ByteArrayInputStream bis) {try {ois.close();bis.close();} catch (IOException e) {e.printStackTrace();}} }

注意: 存入redis的類必須實現序列化接口
步驟4 : 使用 在需要的類中引入即可 RedisCacheService

@Autowiredprivate RedisCacheService redisCacheService;

總結

以上是生活随笔為你收集整理的springboot项目配置redis及其使用------R的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。