日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring boot系列--redis使用之1

發布時間:2023/12/15 javascript 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring boot系列--redis使用之1 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

簡介

在互聯網的應用中,redis被廣泛地使用。而在spring boot中使用redis,是非常簡單的。

spring boot 中的redis

要在spring boot中使用redis,在pom中加入spring-boot-starter-redis依賴。maven會添加spring-data-redis包,其中包含了jedis,jredis,lettuce,srp幾種實現。spring boot缺省選擇jedis實現使用。

jedis配置

缺省使用localhost的redis配置,如果你沒有修改任何配置,在本機上測試,不需要做任何配置。但在生成環境,必須配置真實的環境。

spring:# REDIS (RedisProperties)redis:# Redis數據庫索引(默認為0) database:0# Redis服務器地址host:localhost# Redis服務器連接端口port:6379# Redis服務器連接密碼(默認為空)password:# 連接池最大連接數(使用負值表示沒有限制)pool.max-active:8# 連接池最大阻塞等待時間(使用負值表示沒有限制)pool.max-wait:-1# 連接池中的最大空閑連接pool.max-idle:8# 連接池中的最小空閑連接pool.min-idle:0# 連接超時時間(毫秒)timeout:0

使用StringRedisTemplate來處理String

在spring-data-redis中提供了StringRedisTemplate,可以直接用來處理String數據了。

// 可以直接使用,spring會綁定 @Autowired private StringRedisTemplate template;@RequestMapping("/foo") @ResponseBody public String foo() {ValueOperations<String, String> ops = template.opsForValue();String key = "spring.boot.redis.test";if (!this.template.hasKey(key)) {String str = "not found the key, now set it";log.info(str);ops.set(key, str);return str;} else {String str = "Found key " + key + ", value=" + ops.get(key);log.info(str);return str;}}

可以看一下spring中的實現類:

/** Copyright 2011-2013 the original author or authors.* * Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at* * http://www.apache.org/licenses/LICENSE-2.0* * Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/ package org.springframework.data.redis.core;import org.springframework.data.redis.connection.DefaultStringRedisConnection; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.StringRedisConnection; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer;/*** String-focused extension of RedisTemplate. Since most operations against Redis are String based, this class provides* a dedicated class that minimizes configuration of its more generic {@link RedisTemplate template} especially in terms* of serializers.* <p/>* Note that this template exposes the {@link RedisConnection} used by the {@link RedisCallback} as a* {@link StringRedisConnection}.* * @author Costin Leau*/ public class StringRedisTemplate extends RedisTemplate<String, String> {/*** Constructs a new <code>StringRedisTemplate</code> instance. {@link #setConnectionFactory(RedisConnectionFactory)}* and {@link #afterPropertiesSet()} still need to be called.*/public StringRedisTemplate() {RedisSerializer<String> stringSerializer = new StringRedisSerializer();setKeySerializer(stringSerializer);setValueSerializer(stringSerializer);setHashKeySerializer(stringSerializer);setHashValueSerializer(stringSerializer);}/*** Constructs a new <code>StringRedisTemplate</code> instance ready to be used.* * @param connectionFactory connection factory for creating new connections*/public StringRedisTemplate(RedisConnectionFactory connectionFactory) {this();setConnectionFactory(connectionFactory);afterPropertiesSet();}protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) {return new DefaultStringRedisConnection(connection);} }

在實現中,RedisTemplate和其子類中包含了幾種不同的Serializer,分別對應Key,Value,Hash……,而最簡單的String類型,在stringSerializer變量上實例化為StringRedisSerializer。

public class RedisTemplate<K, V> extends RedisAccessor implements RedisOperations<K, V>, BeanClassLoaderAware {private boolean enableTransactionSupport = false;private boolean exposeConnection = false;private boolean initialized = false;private boolean enableDefaultSerializer = true;private RedisSerializer<?> defaultSerializer;private ClassLoader classLoader;private RedisSerializer keySerializer = null;private RedisSerializer valueSerializer = null;private RedisSerializer hashKeySerializer = null;private RedisSerializer hashValueSerializer = null;private RedisSerializer<String> stringSerializer = new StringRedisSerializer();.../*** Constructs a new <code>RedisTemplate</code> instance.*/public RedisTemplate() {}public void afterPropertiesSet() {super.afterPropertiesSet();boolean defaultUsed = false;if (defaultSerializer == null) {defaultSerializer = new JdkSerializationRedisSerializer(classLoader != null ? classLoader : this.getClass().getClassLoader());}if (enableDefaultSerializer) {if (keySerializer == null) {keySerializer = defaultSerializer;defaultUsed = true;}if (valueSerializer == null) {valueSerializer = defaultSerializer;defaultUsed = true;}if (hashKeySerializer == null) {hashKeySerializer = defaultSerializer;defaultUsed = true;}if (hashValueSerializer == null) {hashValueSerializer = defaultSerializer;defaultUsed = true;}}if (enableDefaultSerializer && defaultUsed) {Assert.notNull(defaultSerializer, "default serializer null and not all serializers initialized");}if (scriptExecutor == null) {this.scriptExecutor = new DefaultScriptExecutor<K>(this);}initialized = true;}}

可以看到spring boot應用在啟動時,如果沒有檢查到對應的對象配置,則最后實例化defaultSerializer對象為JdkSerializationRedisSerializer了。

可以看一下運行時的對象

使用RedisTemplate

在程序中使用 RedisTemplate,如上所說,需要配置對應的serializer,否則對對應的數據處理時,要么serializer對象為null,要么使用的缺省的則使用JdkSerializationRedisSerializer。

要配置我們的redisTemplate對象,可以在配置類中定義一個redisTemplate 的bean。

@Bean public RedisTemplate<String, ? extends Object> redisTemplate( RedisConnectionFactory 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); template.setValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; }

在配置類中,定義了Jackson2JsonRedisSerializer,來作為ValueSerializer對象,對Model對象進行序列化和反序列化。

然后在程序處理的地方,可以使用這個bean對象了。

@Autowired private RedisTemplate redisTemplate;@RequestMapping("/user/{id}") @ResponseBody public String getUser(@PathVariable("id") long id) {log.info("---- getUser");//User user = new User(id, "aa@126.com", "aa", "aa123456", "aa", "123");ValueOperations<String, User> operations = redisTemplate.opsForValue();operations.set("com.dcloud.user", user);// 有超時時間的redis set..operations.set("com.dcloud.user.ex", user, 10, TimeUnit.SECONDS);//boolean exists = redisTemplate.hasKey("com.dcloud.user");if (exists) {log.info("exists is true");} else {log.info("exists is false");}return "finished"; }@RequestMapping(value = "/query") @ResponseBody public String query() {log.info("query from redis");ValueOperations<String, User> operations = redisTemplate.opsForValue();// User ret = operations.get("com.dcloud.user");if (null == ret) {log.info("not exist user");return "finished query, and not exists";}log.info(ret.toString());return "finished query"; }

現在可以看一下運行時的redisTemplate對象

創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的Spring boot系列--redis使用之1的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。