網站首頁 編程語言 正文
springboot中redis相關配置
1、pom.xml中引入依賴
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
2、springboot的習慣優于配置。也在項目中使用了application.yml文件配置mysql的基本配置項。這里也在application.yml里面配置redis的配置項。
spring: datasource: # 驅動配置信息 url: jdbc:mysql://localhost:3306/spring_boot?useUnicode=true&characterEncoding=utf8 username: root password: root type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver # 連接池的配置信息 filters: stat maxActive: 20 initialSize: 1 maxWait: 60000 minIdle: 1 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select 'x' testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxOpenPreparedStatements: 20 redis: host: 127.0.0.1 port: 6379 password: pass1234 pool: max-active: 100 max-idle: 10 max-wait: 100000 timeout: 0
springboot中redis相關類
- 項目操作redis是使用的RedisTemplate方式,另外還可以完全使用JedisPool和Jedis來操作redis。整合的內容也是從網上收集整合而來,網上整合的方式和方法非常的多,有使用注解形式的,有使用Jackson2JsonRedisSerializer來序列化和反序列化key value的值等等,很多很多。這里使用的是我認為比較容易理解和掌握的,基于JedisPool配置,使用RedisTemplate來操作redis的方式。
redis單獨放在一個包redis里,在包里先創建RedisConfig.java文件。
RedisConfig.java
@Configuration @EnableAutoConfiguration public class RedisConfig { @Bean @ConfigurationProperties(prefix = "spring.redis.pool") public JedisPoolConfig getRedisConfig(){ JedisPoolConfig config = new JedisPoolConfig(); return config; } @Bean @ConfigurationProperties(prefix = "spring.redis") public JedisConnectionFactory getConnectionFactory() { JedisConnectionFactory factory = new JedisConnectionFactory(); factory.setUsePool(true); JedisPoolConfig config = getRedisConfig(); factory.setPoolConfig(config); return factory; } @Bean public RedisTemplate<?, ?> getRedisTemplate() { JedisConnectionFactory factory = getConnectionFactory(); RedisTemplate<?, ?> template = new StringRedisTemplate(factory); return template; } }
- 在包里創建RedisService接口的實現類RedisServiceImpl,這個類實現了接口的所有方法。
RedisServiceImpl.java
@Service("redisService") public class RedisServiceImpl implements RedisService { @Resource private RedisTemplate<String, ?> redisTemplate; @Override public boolean set(final String key, final String value) { boolean result = redisTemplate.execute(new RedisCallback<Boolean>() { @Override public Boolean doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = redisTemplate.getStringSerializer(); connection.set(serializer.serialize(key), serializer.serialize(value)); return true; } }); return result; } @Override public String get(final String key) { String result = redisTemplate.execute(new RedisCallback<String>() { @Override public String doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = redisTemplate.getStringSerializer(); byte[] value = connection.get(serializer.serialize(key)); return serializer.deserialize(value); } }); return result; } @Override public boolean expire(final String key, long expire) { return redisTemplate.expire(key, expire, TimeUnit.SECONDS); } @Override public boolean remove(final String key) { boolean result = redisTemplate.execute(new RedisCallback<Boolean>() { @Override public Boolean doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = redisTemplate.getStringSerializer(); connection.del(key.getBytes()); return true; } }); return result; } }
在這里execute()方法具體的底層沒有去研究,只知道這樣能實現對于redis數據的操作。
redis保存的數據會在內存和硬盤上存儲,所以需要做序列化;這個里面使用的StringRedisSerializer來做序列化,不過這個方式的泛型指定的是String,只能傳String進來。所以項目中采用json字符串做redis的交互。
到此,redis在springboot中的整合已經完畢,下面就來測試使用一下。
5. springboot項目中使用redis
在這里就直接使用springboot項目中自帶的單元測試類SpringbootApplicationTests進行測試。
@RunWith(SpringRunner.class) @SpringBootTest public class SpringbootApplicationTests { private JSONObject json = new JSONObject(); @Autowired private RedisService redisService; @Test public void contextLoads() throws Exception { } /** * 插入字符串 */ @Test public void setString() { redisService.set("redis_string_test", "springboot redis test"); } /** * 獲取字符串 */ @Test public void getString() { String result = redisService.get("redis_string_test"); System.out.println(result); } /** * 插入對象 */ @Test public void setObject() { Person person = new Person("person", "male"); redisService.set("redis_obj_test", json.toJSONString(person)); } /** * 獲取對象 */ @Test public void getObject() { String result = redisService.get("redis_obj_test"); Person person = json.parseObject(result, Person.class); System.out.println(json.toJSONString(person)); } /** * 插入對象List */ @Test public void setList() { Person person1 = new Person("person1", "male"); Person person2 = new Person("person2", "female"); Person person3 = new Person("person3", "male"); List<Person> list = new ArrayList<>(); list.add(person1); list.add(person2); list.add(person3); redisService.set("redis_list_test", json.toJSONString(list)); } /** * 獲取list */ @Test public void getList() { String result = redisService.get("redis_list_test"); List<String> list = json.parseArray(result, String.class); System.out.println(list); } @Test public void remove() { redisService.remove("redis_test"); } } class Person { private String name; private String sex; public Person() { } public Person(String name, String sex) { this.name = name; this.sex = sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
在這里先是用@Autowired注解把redisService注入進來,然后由于是使用json字符串進行交互,所以引入fastjson的JSONObject類。然后為了方便,直接在這個測試類里面加了一個Person的內部類。
一共測試了:對于string類型的存取,對于object類型的存取,對于list類型的存取,其實本質都是轉成了json字符串。還有就是根據key來執行remove操作。
獲取字符串:
獲取對象:
獲取list:
redis管理客戶端數據:
到此,測試完成,對于常用的一些數據類型的轉換存取操作也基本調試通過。所以本文對于springboot整合redis到此結束。
原文鏈接:https://www.cnblogs.com/hongmaju/p/15726547.html
相關推薦
- 2022-03-14 【錯誤記錄/html】Response to preflight request doesn‘t p
- 2022-04-07 Go語言中int、float、string類型之間相互的轉換_Golang
- 2023-04-02 攔截信號Golang應用優雅關閉的操作方法_Golang
- 2022-07-14 浮點數乘法和整形乘除法的效率經驗比較_C 語言
- 2022-10-03 使用useImperativeHandle時父組件第一次沒拿到子組件的問題_React
- 2022-05-14 Python函數中的作用域規則詳解_python
- 2022-08-25 C++淺析STL?迭代器?容器的使用_C 語言
- 2023-03-20 Linq利用Distinct去除重復項問題(可自己指定)_C#教程
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支