基礎使用
首先引入依賴
<!-- redis依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
然后在application.yml的spring下增加redis配置:

代碼如下
redis: # Redis資料庫索引(默認為0) database: 0 # Redis服務器地址 host: 127.0.0.1 # Redis服務器連接埠 port: 6379 password: '123456' jedis: pool: # 連接池最大連接數(使用負值表示沒有限制) max-active: 8 # 連接池最大阻塞等待時間(使用負值表示沒有限制) max-wait: 1 # 連接池中的最大空閑連接 max-idle: 8 # 連接池中的最小空閑連接 min-idle: 0 # 連接超時時間(毫秒) timeout: 5000
然后在根包下創建一個service的檔案夾加,然后在里面增加redis檔案夾,redis檔案夾里撰寫redis的基礎操作函式,
撰寫IRedisService介面,撰寫增刪改查函式,代碼如下:
import java.util.Map; ? @Service public interface IRedisService { /** * 加入元素 * @param key * @param value */ void setValue(String key, Map<String, Object> value); /** * 加入元素 * @param key * @param value */ void setValue(String key, String value); /** * 加入元素 * @param key * @param value */ void setValue(String key, Object value); /** * 獲取元素 * @param key */ Object getMapValue(String key); /** * 獲取元素 * @param key */ Object getValue(String key); ? }
撰寫RedisServiceImpl實作,實作Redis的增刪改查,
package com.example.dynamicdb.service.redis; ? import org.springframework.beans.factory.annotation.Autowired; ? import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Service; ? import java.util.Map; import java.util.concurrent.TimeUnit; ? @Service("RedisServiceImpl") public class RedisServiceImpl implements IRedisService { ? public RedisServiceImpl(){} ? @Autowired private RedisTemplate redisTemplate; ? ? @Override public void setValue(String key, Map<String, Object> value) { ValueOperations<String, Object> vo = redisTemplate.opsForValue(); vo.set(key, value); redisTemplate.expire(key, 1, TimeUnit.HOURS); } ? @Override public Object getValue(String key) { ValueOperations<String, String> vo = redisTemplate.opsForValue(); return vo.get(key); } ? @Override public void setValue(String key, String value) { ValueOperations<String, Object> vo = redisTemplate.opsForValue(); vo.set(key, value); redisTemplate.expire(key, 1, TimeUnit.HOURS); } ? @Override public void setValue(String key, Object value) { ValueOperations<String, Object> vo = redisTemplate.opsForValue(); vo.set(key, value); redisTemplate.expire(key, 1, TimeUnit.HOURS); } ? @Override public Object getMapValue(String key) { ValueOperations<String, String> vo = redisTemplate.opsForValue(); return vo.get(key); } ? }
然后創建一個RedisController,撰寫一個測驗介面,如下:
@RestController
public class RedisController {
@Resource(name = "RedisServiceImpl")//使用resource實體化物件,name是指定實體化的類,用于一個介面多個類繼承的情況
private IRedisService iRedisService;
@PostMapping(value = "https://www.cnblogs.com/Redis/TestRedis")
@ApiOperation(value = "https://www.cnblogs.com/kiba/archive/2023/06/14/redis測驗介面", notes = "redis測驗介面", httpMethod = "POST")
public String TestRedis(){
iRedisService.setValue("redis", "這是redis的測驗資料");
Object redis = iRedisService.getValue("redis");
return redis.toString();
}
}
redis快取使用
首先創建一個config檔案夾,然后創建一個RedisCacheConfig檔案,代碼如下:
?
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
?
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
?
@EnableCaching
@Configuration
public class RedisCacheConfig {
?
?
/**
* 最新版,設定redis快取過期時間
*/
?
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
return new RedisCacheManager(
RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
this.getRedisCacheConfigurationWithTtl( 60), // 默認策略,未配置的 key 會使用這個
this.getRedisCacheConfigurationMap() // 指定 key 策略
);
}
?
private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
//SsoCache和BasicDataCache進行過期時間配置
redisCacheConfigurationMap.put("messagCache", this.getRedisCacheConfigurationWithTtl(30 * 60));
?
//自定義設定快取時間
redisCacheConfigurationMap.put("studentCache", this.getRedisCacheConfigurationWithTtl(60 ));
?
return redisCacheConfigurationMap;
}
?
private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
Jackson2JsonRedisSerializer<Object> 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);
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
RedisSerializationContext
.SerializationPair
.fromSerializer(jackson2JsonRedisSerializer)
).entryTtl(Duration.ofSeconds(seconds));
?
return redisCacheConfiguration;
}
}
類名上有注解@Configuration,代表該類會在啟動時加入進bean集合,
然后在RedisController下撰寫測驗函式,如下:
@Autowired
private SqlSession sqlSession;
@GetMapping(value = "https://www.cnblogs.com/Redis/TestRedisCache")
@ResponseBody
@DS("db2")
@Cacheable(cacheNames = "userCache", key = "#id")
@ApiOperation(value="https://www.cnblogs.com/kiba/archive/2023/06/14/查詢單條記錄",notes = "查詢")
public List<user> TestRedisCache(Integer id) {
//讀取第二個資料庫的值
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<user> users = mapper.test();
return users;
}
使用@Cacheable注解快取介面的回傳值,cacheNames的值和key的值,組合起來成為是快取中的鍵值對的key值,如下圖,

----------------------------------------------------------------------------------------------------
到此,SpringBoot中Redis的基礎使用就已經介紹完了,
代碼已經傳到Github上了,歡迎大家下載,
Github地址:https://github.com/kiba518/dynamicdb
----------------------------------------------------------------------------------------------------
注:此文章為原創,任何形式的轉載都請聯系作者獲得授權并注明出處!
若您覺得這篇文章還不錯,請點擊下方的【推薦】,非常感謝!
https://www.cnblogs.com/kiba/p/17480377.html

https://www.cnblogs.com/kiba/
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/555179.html
標籤:其他
上一篇:Java多執行緒開發系列之六:無限分解流----Fork/Join框架
下一篇:返回列表
