溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Spring Boot如何快速集成Redis

發布時間:2020-07-15 16:13:41 來源:億速云 閱讀:158 作者:小豬 欄目:開發技術

這篇文章主要為大家展示了Spring Boot 如何快速集成 Redis,內容簡而易懂,下面讓小編帶大家一起學習一下吧。

添加依賴

使用像 Redis 這類的 NoSQL 數據庫就必須要依賴 spring-data-redis 這樣的能力包,開箱即用,Spring Boot 中都封裝好了:

引入spring-boot-starter-data-redis:

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

Spring Boot 基礎知識就不介紹了,不熟悉的可以關注公眾號Java技術棧,在后臺回復:boot,可以閱讀我寫的歷史實戰教程。

它主要包含了下面四個依賴:

  • spring-boot-dependencies
  • spring-boot-starter
  • spring-data-redis
  • lettuce-core

添加 Redis 連接配置

Redis 自動配置支持配置單機、集群、哨兵,來看下 RedisProperties 的參數類圖吧:

Spring Boot如何快速集成Redis

本文以單機為示例,我們在 application.yml 配置文件中添加 Redis 連接配置,:

spring:
  redis:
    host: 192.168.8.88
    port: 6379
    password: redis2020
    database: 1

也可以將參數配置在 Spring Cloud Config Server 配置中心中。

Redis 自動配置

添加完依賴和連接配置參數之后,Redis 就能自動配置,參考 Redis 的自動配置類:

org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration

源碼:

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
public class RedisAutoConfiguration {

    ...

}

通過看源碼,Redis內置兩種客戶端的自動配置:

1)Lettuce(默認):

org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration

2)Jedis:

org.springframework.boot.autoconfigure.data.redis.JedisConnectionConfiguration

為什么默認Lettuce,其實文章之前的四個依賴也看出來了,請看默認依賴:

Spring Boot如何快速集成Redis

自動配置提供了兩種操作模板:

1)RedisTemplate<Object, Object>

key-value 都為 Object 對象,并且默認用的 JDK 的序列化/反序列化器:

org.springframework.data.redis.serializer.JdkSerializationRedisSerializer

使用這個序列化器,key 和 value 都需要實現 java.io.Serializable 接口。

2)StringRedisTemplate

key-value 都為 String 對象,默認用的 String UTF-8 格式化的序列化/反序列化器:

org.springframework.data.redis.serializer.StringRedisSerializer

上面提到了兩種序列化器,另外還有兩種 JSON 的序列化器值得學習一下,下面配置會用到。

  • Jackson2JsonRedisSerializer
  • GenericJackson2JsonRedisSerializer

使用方式上,兩種都可以序列化、反序列化 JSON 數據,Jackson2JsonRedisSerializer 效率高,但 GenericJackson2JsonRedisSerializer 更為通用,不需要指定泛型類型。

核心配置

除了自動配置之外,下面是 Redis 的核心配置,主要是自定義了 RedisTemplate 使用 JSON 序列化器。

另外就是,把幾個數據類型的操作類進行了 Bean 池化處理。

@Configuration
public class RedisConfig {

 @Bean
 public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
  RedisTemplate<String, Object> template = new RedisTemplate<>();
  template.setConnectionFactory(factory);

  StringRedisSerializer stringSerializer = new StringRedisSerializer();

  RedisSerializer jacksonSerializer = getJacksonSerializer();

  template.setKeySerializer(stringSerializer);
  template.setValueSerializer(jacksonSerializer);
  template.setHashKeySerializer(stringSerializer);
  template.setHashValueSerializer(jacksonSerializer);
  template.setEnableTransactionSupport(true);
  template.afterPropertiesSet();

  return template;
 }

 private RedisSerializer getJacksonSerializer() {
  ObjectMapper om = new ObjectMapper();
  om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  return new GenericJackson2JsonRedisSerializer(om);
 }

 @Bean
 public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
  return redisTemplate.opsForHash();
 }

 @Bean
 public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
  return redisTemplate.opsForValue();
 }

 @Bean
 public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
  return redisTemplate.opsForList();
 }

 @Bean
 public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
  return redisTemplate.opsForSet();
 }

 @Bean
 public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
  return redisTemplate.opsForZSet();
 }

}

如果你只想用默認的 JDK 序列化器,那 RedisTemplate 相關配置就不是必須的。

緩存實戰

下面寫了一個示例,用來緩存并讀取緩存中一個類對象。

@GetMapping("/redis/set")
public String set(@RequestParam("name") String name) {
 User user = new User();
 user.setId(RandomUtils.nextInt());
 user.setName(name);
 user.setBirthday(new Date());

 List<String> list = new ArrayList<>();
 list.add("sing");
 list.add("run");
 user.setInteresting(list);

 Map<String, Object> map = new HashMap<>();
 map.put("hasHouse", "yes");
 map.put("hasCar", "no");
 map.put("hasKid", "no");
 user.setOthers(map);

 redisOptService.set(name, user, 30000);
 User userValue = (User) redisOptService.get(name);
 return userValue.toString();
}

測試:

http://localhost:8080/redis/set&#63;name=zhangsan

返回:

User(id=62386235, name=zhangsan, birthday=Tue Jun 23 18:04:55 CST 2020, interesting=[sing, run], others={hasHouse=yes, hasKid=no, hasCar=no})

Redis中的值:

192.168.8.88:6379> get zhangsan
"["cn.javastack.springboot.redis.pojo.User",{"id":62386235,"name":"zhangsan","birthday":["java.util.Date",1592906695750],"interesting":["java.util.ArrayList",["sing","run"]],"others":["java.util.HashMap",{"hasHouse":"yes","hasKid":"no","hasCar":"no"}]}]"

以上就是關于Spring Boot 如何快速集成 Redis的內容,如果你們有學習到知識或者技能,可以把它分享出去讓更多的人看到。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女