springboot使用redisRepository和redistemplate操作redis的過程解析
導(dǎo)入依賴
菜單大部分情況下不會出現(xiàn)變化,我們可以將其放入Redis 加快加載速度
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- commons-pool2 對象池依賴 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency>
基本配置
redis: timeout: 10000ms # 連接超時時間 host: 192.168.10.100 # Redis服務(wù)器地址 port: 6379 # Redis服務(wù)器端口 database: 0 # 選擇哪個庫,默認0庫 lettuce: pool: max-active: 1024 # 最大連接數(shù),默認 8 max-wait: 10000ms # 最大連接阻塞等待時間,單位毫秒,默認 -1 max-idle: 200 # 最大空閑連接,默認 8 min-idle: 5 # 最小空閑連接,默認 0
使用RedisTemplate訪問redis
RedisConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import
org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import
org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* Redis配置類
*
* @author zhoubin
* @since 1.0.0
*/
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String,Object> redisTemplate(LettuceConnectionFactory
redisConnectionFactory){
RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
//為string類型key設(shè)置序列器
redisTemplate.setKeySerializer(new StringRedisSerializer());
//為string類型value設(shè)置序列器
redisTemplate.setValueSerializer(new
GenericJackson2JsonRedisSerializer());
//為hash類型key設(shè)置序列器
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
//為hash類型value設(shè)置序列器
redisTemplate.setHashValueSerializer(new
GenericJackson2JsonRedisSerializer());
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
}
}
修改菜單方法:
MenuServiceImpl.java
/**
* 通過用戶id獲取菜單列表
*
* @return
*/
@Override
public List<Menu> getMenusByAdminId() {
Integer adminId = ((Admin)
SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
ValueOperations<String, Object> valueOperations =
redisTemplate.opsForValue();
//查詢緩存中是否有數(shù)據(jù)
List<Menu> menus = (List<Menu>) valueOperations.get("menu_" + adminId);
if (CollectionUtils.isEmpty(menus)){
menus = menuMapper.getMenusByAdminId(adminId);
valueOperations.set("menu_"+adminId,menus);
}
return menus;
}
使用Redisrepository訪問redis
需要聲明一配置項用于啟用Repository以及模板
public class RedisConfig {
@Bean
public LettuceConnectionFactory redisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration("127.0.0.1", 6567);
redisStandaloneConfiguration.setPassword("password");//如果有密碼需要通過這個函數(shù)設(shè)置密碼
return new LettuceConnectionFactory(redisStandaloneConfiguration);
}
@Bean
public JedisConnectionFactory jedisConnectionFactory(){
//如果使用jedis作為客戶端也需要聲明該bean 使用與上面的類似
}
@Bean
public RedisTemplate<?,?> redisTemplate(){
RedisTemplate<String,Object> template = new RedisTemplate<>();
RedisSerializer<String> stringSerializer = new StringRedisSerializer();
JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer();
template.setConnectionFactory(redisConnectionFactory());
template.setKeySerializer(stringSerializer);
template.setHashKeySerializer(stringSerializer);
template.setValueSerializer(stringSerializer);
template.setHashValueSerializer(jdkSerializationRedisSerializer);
template.setEnableTransactionSupport(true);
template.afterPropertiesSet();
return template;
}
}
實例:
entity
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.data.redis.core.RedisHash;
import org.springframework.data.redis.core.index.Indexed;
@Accessors(chain = true)
@Data
@RedisHash(value="Student",timeToLive = 10)
public class stu implements Serializable {
public enum Gender{
MALE,FEMALE
}
private String id;
@Indexed
private String name;
private Gender gender;
//RedisHash注解用于聲明該實體將被存儲與RedisHash中,如果需要使用repository的數(shù)據(jù)訪問形式,這個注解是必須用到的 timetoLive為實體對象在數(shù)據(jù)庫的有效期
//@Indexed用于標(biāo)注需要作為查詢條件的屬性
}寫接口
repository:
@Repository
public interface StuRepository extends CrudRepository<stu,String> {
stu findByName(String name);
//自定義查詢方法,使用了@Indexed的name屬性查詢
}
調(diào)用:
@SpringBootTest
public class RedisApplicationTests {
@Autowired
StuRepository stuRepository;
@Test
void testSave(){
stu student = new stu().setId("0002").setName("xiaoming").setGender(stu.Gender.FEMALE);
stuRepository.save(student);//根據(jù)id更新或者新增記錄
}
@Test
void testFindBy(){
//使用主鍵查詢
assert stuRepository.findById("0002").isPresent();
//根據(jù)自定義方法查詢
assert stuRepository.findByName("xiaoming") !=null;
}
}到此這篇關(guān)于springboot使用redisRepository和redistemplate操作redis的過程解析的文章就介紹到這了,更多相關(guān)springboot整合redis內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 在SpringBoot中注入RedisTemplate實例異常的解決方案
- SpringBoot整合Redis使用@Cacheable和RedisTemplate
- SpringBoot整合RedisTemplate實現(xiàn)緩存信息監(jiān)控的步驟
- 詳解SpringBoot使用RedisTemplate操作Redis的5種數(shù)據(jù)類型
- SpringBoot整合Redis使用RedisTemplate和StringRedisTemplate
- SpringBoot混合使用StringRedisTemplate和RedisTemplate的坑及解決
- SpringBoot集成RedisTemplate的實現(xiàn)示例
相關(guān)文章
Java中if...else語句使用的學(xué)習(xí)教程
這篇文章主要介紹了Java中if...else語句使用的學(xué)習(xí)教程,是Java入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2015-11-11
Java內(nèi)存分配與JVM參數(shù)詳解(推薦)
本文詳解JVM內(nèi)存結(jié)構(gòu)與參數(shù)調(diào)整,涵蓋堆分代、元空間、GC選擇及優(yōu)化策略,幫助開發(fā)者提升性能、避免內(nèi)存泄漏,本文給大家介紹Java內(nèi)存分配與JVM參數(shù)詳解,感興趣的朋友一起看看吧2025-06-06
使用JMeter從JSON響應(yīng)的URL參數(shù)中提取特定值
在使用Apache JMeter進行API測試時,我們經(jīng)常需要從JSON格式的響應(yīng)中提取特定字段的值,這可以通過使用JMeter內(nèi)置的JSON提取器和正則表達式提取器來完成,本文介紹JMeter JSON提取特定值的相關(guān)知識,感興趣的朋友跟隨小編一起看看吧2024-03-03
spring?boot?實現(xiàn)一個?禁止重復(fù)請求的方法
這篇文章主要介紹了spring?boot?實現(xiàn)一個?禁止重復(fù)請求,當(dāng)重復(fù)請求該方法時,會返回"Duplicate?request",避免重復(fù)執(zhí)行相同的操作,需要的朋友可以參考下2024-03-03
mybatis如何在一個update標(biāo)簽中寫多條update語句
這篇文章主要介紹了mybatis如何在一個update標(biāo)簽中寫多條update語句問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08
詳解SpringMVC的url-pattern配置及原理剖析
這篇文章主要介紹了SpringMVC的url-pattern配置及原理剖析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06

