redis怎么在springboot中使用?針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡單易行的方法。
創(chuàng)新互聯(lián)公司網(wǎng)站建設(shè)由有經(jīng)驗(yàn)的網(wǎng)站設(shè)計(jì)師、開發(fā)人員和項(xiàng)目經(jīng)理組成的專業(yè)建站團(tuán)隊(duì),負(fù)責(zé)網(wǎng)站視覺設(shè)計(jì)、用戶體驗(yàn)優(yōu)化、交互設(shè)計(jì)和前端開發(fā)等方面的工作,以確保網(wǎng)站外觀精美、成都網(wǎng)站制作、做網(wǎng)站易于使用并且具有良好的響應(yīng)性。
安裝 redis
通過 docker 安裝,docker compose 編排文件如下:
# docker-compose.yml version: "2" services: redis: container_name: redis image: redis:3.2.10 ports: - "6379:6379"
然后在docker-compose.yml
所在目錄使用docker-compose up -d
命令,啟動(dòng) redis。
集成 springboot
說明:springboot 版本為 2.1.3
添加 maven 依賴
只需添加spring-boot-starter-data-redis依賴即可,并排除 lettuce 依賴,然后引入 jedis 和 jedis 的依賴 commons-pool2
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <exclusions> <exclusion> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency>
編寫 springboot 配置文件
配置文件如下:
server: port: 8081 servlet: context-path: /sso spring: application: name: SSO cache: type: redis redis: database: 0 host: 192.168.226.5 port: 6379 # 有密碼填密碼,沒有密碼不填 password: # 連接超時(shí)時(shí)間(ms) timeout: 1000ms # 高版本springboot中使用jedis或者lettuce jedis: pool: # 連接池最大連接數(shù)(負(fù)值表示無限制) max-active: 8 # 連接池最大阻塞等待時(shí)間(負(fù)值無限制) max-wait: 5000ms # 最大空閑鏈接數(shù) max-idle: 8 # 最小空閑鏈接數(shù) min-idle: 0
編寫配置類
配置類代碼如下:
@EnableCaching//開啟緩存 @Configuration public class RedisConfig extends CachingConfigurerSupport { /** * 設(shè)置緩存管理器,這里可以配置默認(rèn)過期時(shí)間等 * * @param connectionFactory 連接池 * @return */ @Bean public CacheManager cacheManager(RedisConnectionFactory connectionFactory) { RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration .defaultCacheConfig() .entryTtl(Duration.ofSeconds(60)); //注意:請(qǐng)勿使用先new 配置對(duì)象,然后在調(diào)用entryTtl方法的方式來操作 //會(huì)導(dǎo)致配置不生效,原因是調(diào)用.entryTtl方法會(huì)返回一個(gè)新的配置對(duì)象,而不是在原來的配置對(duì)象上修改 RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory); RedisCacheManager manager = new RedisCacheManager(redisCacheWriter, redisCacheConfiguration); return manager; } @SuppressWarnings("all") @Bean public RedisTemplate<String, String> redisTemplate(JedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); Jackson2JsonRedisSerializer 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); RedisSerializer stringSerializer = new StringRedisSerializer(); template.setKeySerializer(stringSerializer); template.setValueSerializer(jackson2JsonRedisSerializer); template.setHashKeySerializer(stringSerializer); template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } //使用jedis連接池建立jedis連接工廠 @Bean public JedisConnectionFactory jedisConnectionFactory() { logger.info("jedisConnectionFactory:初始化了"); JedisPoolConfig config = new JedisPoolConfig(); config.setMaxIdle(maxIdle); config.setMinIdle(minIdle); config.setMaxWaitMillis(maxWaitMillis); config.setMaxTotal(maxActive); //鏈接耗盡時(shí)是否阻塞,默認(rèn)true config.setBlockWhenExhausted(true); //是否啟用pool的jmx管理功能,默認(rèn)true config.setJmxEnabled(true); JedisConnectionFactory factory = new JedisConnectionFactory(); factory.setPoolConfig(config); factory.setHostName(host); factory.setPort(port); factory.setPassword(password); factory.setDatabase(database); factory.setTimeout(timeout); return factory; } }
使用方法
有兩種方法來進(jìn)行緩存操作,一種是在方法上添加緩存注解實(shí)現(xiàn)各種操作,一種是手動(dòng)控制。個(gè)人比較喜歡手動(dòng)控制,覺得這樣都在自己的掌控中。
通過注解使用
主要有以下 5 個(gè)注解:
?@CacheConfig: 類級(jí)別緩存,設(shè)置緩存 key 前綴之類的
?@Cacheable: 觸發(fā)緩存入口
?@CacheEvict: 觸發(fā)移除緩存
?@CachePut: 更新緩存
?@Caching: 組合緩存
@CacheConfig
該注解可以將緩存分類,它是類級(jí)別注解,主要用于給某個(gè)類的緩存全局配置,例子如下:
@CacheConfig(cacheNames = "redis_test") @Service public class RedisService { //.... }
上面 CacheConfig 會(huì)給類下通過注解生成的 key 加上 redis_test
的前綴。
@Cacheable
方法級(jí)別注解,根據(jù) key 查詢緩存:
?如果 key 不存在,將方法返回值緩存到 redis 中
?如果 key 存在,直接從緩存中取值
例子如下:
/** * 緩存時(shí)間,首次查詢后會(huì)緩存結(jié)果,key中的值可使用表達(dá)式計(jì)算. * 如不提供key,將使用默認(rèn)key構(gòu)造方法生成一個(gè)key * @return long */ @Cacheable(key = "'currentTime'") public long getTime() { return System.currentTimeMillis(); }
多次調(diào)用此段代碼會(huì)發(fā)現(xiàn)每次返回的值都是一樣的。
CachePut
用于更新緩存,每次調(diào)用都會(huì)想 db 請(qǐng)求,緩存數(shù)據(jù)
?如果 key 存在,更新內(nèi)容
?如果 key 不存在,插入內(nèi)容
代碼如下:
/** * 一般用于更新查插入操作,每次都會(huì)請(qǐng)求db */ @CachePut(key = "'currentTime'+#id") public long updateTime(String id) { return System.currentTimeMillis(); }
每次調(diào)用此方法都會(huì)根據(jù) key 刷新 redis 中的緩存數(shù)據(jù)。
@CacheEvict
根據(jù) key 刪除緩存中的數(shù)據(jù)。allEntries=true
表示刪除緩存中所有數(shù)據(jù)。
代碼如下:
@CacheEvict(key = "'currentTime'+#id",allEntries=false) public void deleteTime(String id) { }
@Caching
本注解可將其他注解組合起來使用。比如下面的例子:
//value屬性為key指定前綴 @Caching(put = {@CachePut(value = "user", key = "'name_'+#user.name"), @CachePut(value = "user", key = "'pass_'+#user.password")}) public User testCaching(User user) { return user; }
上面的代碼執(zhí)行后將在 redis 中插入兩條記錄。使用keys *
將看到如下結(jié)果:
手動(dòng)控制
手動(dòng)控制就相當(dāng)于 mybatis 的手寫 sql 語句,需要調(diào)用redisTemplate
中的各種方法來進(jìn)行緩存查詢,緩存更新,緩存刪除等操作。
使用方法參見 util/RedisUtil 中的方法。redisTemplate
基本可以實(shí)現(xiàn)所有的 redis 操作。
關(guān)于redis怎么在springboot中使用問題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
分享標(biāo)題:redis怎么在springboot中使用
網(wǎng)頁鏈接:http://aaarwkj.com/article48/jjpcep.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站建設(shè)、外貿(mào)網(wǎng)站建設(shè)、企業(yè)建站、面包屑導(dǎo)航、網(wǎng)站維護(hù)、用戶體驗(yàn)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)