首頁  >  文章  >  資料庫  >  SpringBoot如何配置Redis高並發緩存

SpringBoot如何配置Redis高並發緩存

WBOY
WBOY轉載
2023-05-27 14:26:271454瀏覽

1.引入依賴

 <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
 </dependency>

2.設定

#
#启动redis
#redis的数据库索引(默认为0)
spring.redis.database=2
#redis的服务器地址
spring.redis.host=127.0.0.1
#密码(没有就为空)
spring.redis.password=
#连接池的最大连接数
spring.redis.jedis.pool.max-active=2000
#连接池的最大阻塞等待时间(使用负值表示无限制)
spring.redis.jedis.pool.max-wait=-1
#连接池的最小空闲连接
spring.redis.jedis.pool.min-idle=50
#连接超时时间(毫秒)
spring.redis.timeout=1000



#集群模式配置
#spring.redis.cluster.nodes=106.54.79.43:7001,106.54.79.43:7002,106.54.79.43:7003,106.54.79.43:7004,106.54.79.43:7005,106.54.79.43:7006

3.自動組裝的物件

@AutowiredStringRedisTemplate stringRedisTemplate;//仅支持字符串的数据@AutowiredRedisTemplate redisTemplate;//支持对象的数据,但需要对对象进行序列化

4.序列化

什麼是序列化?

序列化是將物件狀態轉換為可保持或傳輸的格式的過程。與序列化相對的是反序列化,它將流轉換為物件。這兩個過程結合起來,可以輕鬆地儲存和傳輸資料。

為什麼要序列化物件

把物件轉換為位元組序列的過程稱為物件的序列化把位元組序列還原為物件的過程稱為物件的反序列​​化

@Configuration@AutoConfigureAfter(RedisAutoConfiguration.class)public class RedisConfig {/**java项目www.1b23.com
     * 对属性进行序列化和创建连接工厂
     * @param connectionFactory
     * @return
     */@Beanpublic RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory connectionFactory) {RedisTemplate<String, Serializable> template = new RedisTemplate<>();template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(new GenericJackson2JsonRedisSerializer());template.setConnectionFactory(connectionFactory);return template;}}

5.測試

//java项目www.1b23.com@RequestMapping("/user")@RestControllerpublic class UserController {@AutowiredStringRedisTemplate stringRedisTemplate;//仅支持字符串的数据@AutowiredRedisTemplate redisTemplate;//支持对象的数据,前提需要进行序列化@GetMappingpublic User user(){User user = new User();user.setId("1");user.setName("zhangshan");user.setPhone("133333333");//插入数据        stringRedisTemplate.opsForValue().set("1",user.toString());redisTemplate.opsForValue().set("user",user);//        return stringRedisTemplate.opsForValue().get("1");   return (User)redisTemplate.opsForValue().get("user");}}

以上是SpringBoot如何配置Redis高並發緩存的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除