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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

从.Net到Java学习第四篇——spring boot+redis

發布時間:2023/12/10 asp.net 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 从.Net到Java学习第四篇——spring boot+redis 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

從.Net到Java學習系列目錄

“學習java已經十天,有時也懷念當初.net的經典,讓這語言將你我相連,懷念你......”接上一篇,本篇使用到的框架redis、FastJSON。

環境準備

安裝redis,下圖是我本機的redis綠色版,你可以網上自行下載安裝,如果不知道如何怎么操作,可以移步到我的另一篇文章:ASP.NET Redis 開發

以管理員身份打開CMD窗口:

C:\Users\zouqj>e:E:\>cd E:\Redis-x64-3.2.100E:\Redis-x64-3.2.100>redis-server --service-install redis.windows.conf --loglevel verbose --service-name redis --port 6379

運行之后,記得啟動redis服務,我這里redis沒有設置密碼。

啟動服務命令:net start redis

關于FastJSON框架的使用呢可以參考文章:高性能JSON框架之FastJson的簡單使用

修改pom.xml,添加redis的依賴

<!--redis--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-redis</artifactId><version>1.3.8.RELEASE</version></dependency><!--JSON--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.1.23</version></dependency>

修改項目配置文件,添加如下配置節點

redis:database: 0host: 127.0.0.1port: 6379pool:max-active: 100max-idle: 10max-wait: 100000timeout: 0

最終配置如下:

redis配置項說明:

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

新建一個redis的配置類RedisConfig,因為是配置類,所以要在類上面添加注解@Configuration

@EnableAutoConfiguration注解我們看下它的源碼,發現它是一個組合注解

@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @AutoConfigurationPackage @Import({EnableAutoConfigurationImportSelector.class}) public @interface EnableAutoConfiguration {String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";Class<?>[] exclude() default {};String[] excludeName() default {}; }

@EnableAutoConfiguration注解大致處理流程就是:
1、先去掃描已經被@Component所注釋的類,當然會先判斷有沒有@Condition相關的注解。
2、然后遞歸的取掃描該類中的@ImportResource,@PropertySource,@ComponentScan,@Bean,@Import。一直處理完。

參考:@EnableAutoConfiguration 配置解釋

@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;}@Beanpublic RedisTemplate<?, ?> getRedisTemplate() {JedisConnectionFactory factory = getConnectionFactory();RedisTemplate<?, ?> template = new StringRedisTemplate(factory);return template;} }

添加一個redis的接口服務RedisService

package com.yujie.service;public interface RedisService {/*** set存數據 * @param key * @param value * @return*/boolean set(String key, String value);/*** get獲取數據 * @param key * @return*/String get(String key);/*** 設置有效天數 * @param key * @param expire * @return*/boolean expire(String key, long expire);/*** 移除數據 * @param key * @return*/boolean remove(String key);}

添加redis實現類RedisServiceImpl,注意下面代碼中標紅了的代碼,這里設置redis的key和value以字符串的方式進行存儲,如果不配置的話,默認是以16進制的形式進行存儲,到時候我們讀取的時候,就會看著很亂。

@Service("redisService") public class RedisServiceImpl implements RedisService {@Resourceprivate RedisTemplate<String, ?> redisTemplate;@Overridepublic boolean set(final String key, final String value) {boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {@Overridepublic Boolean doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = redisTemplate.getStringSerializer();connection.set(serializer.serialize(key), serializer.serialize(value));return true;}});return result;}@Overridepublic String get(final String key) {String result = redisTemplate.execute(new RedisCallback<String>() {@Overridepublic String doInRedis(RedisConnection connection) throws DataAccessException {RedisSerializer<String> serializer = redisTemplate.getStringSerializer();byte[] value = connection.get(serializer.serialize(key));return serializer.deserialize(value);}});return result;}@Overridepublic boolean expire(final String key, long expire) {return redisTemplate.expire(key, expire, TimeUnit.SECONDS);}@Overridepublic boolean remove(final String key) {boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {@Overridepublic Boolean doInRedis(RedisConnection connection) throws DataAccessException {RedisSerializer<String> serializer = redisTemplate.getStringSerializer();connection.del(key.getBytes());return true;}});return result;} }

由于項目中引入了spring-boot-starter-test的依賴,也就是集成了spring boot的單元測試框架。給redis實現類,添加單元測試,將光標移動到RedisService接口位置處,然后按Alt+Enter,如下圖所示:

全選所有方法

在model包中,添加一個實體類Person

public 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;} }

接下來,我們再修改一下單元測試

@RunWith(SpringRunner.class) @SpringBootTest public class RedisServiceImplTest {private JSONObject json = new JSONObject();@Autowiredprivate RedisService redisService;@Testpublic void contextLoads() throws Exception {}/*** 插入字符串*/@Testpublic void setString() {redisService.set("redis_string_test", "springboot redis test");}/*** 獲取字符串*/@Testpublic void getString() {String result = redisService.get("redis_string_test");System.out.println(result);}/*** 插入對象*/@Testpublic void setObject() {Person person = new Person("person", "male");redisService.set("redis_obj_test", json.toJSONString(person));}/*** 獲取對象*/@Testpublic void getObject() {String result = redisService.get("redis_obj_test");Person person = json.parseObject(result, Person.class);System.out.println(json.toJSONString(person));}/*** 插入對象List*/@Testpublic 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*/@Testpublic void getList() {String result = redisService.get("redis_list_test");List<String> list = json.parseArray(result, String.class);System.out.println(list);}@Testpublic void remove() {redisService.remove("redis_test");}} View Code

?我們發現,在單元測試類上面自動添加了2個注解,@SpringBootTest@RunWith(SpringRunner.class)

@SpringBootTest注解是SpringBoot自1.4.0版本開始引入的一個用于測試的注解。

@RunWith就是一個運行器

@RunWith(SpringRunner.class)就是指用SpringRunner來運行

運行單元測試:

查看redis中的結果,這里用到一個可視化的redis管理工具:RedisDesktopManager

轉載于:https://www.cnblogs.com/jiekzou/p/9205117.html

總結

以上是生活随笔為你收集整理的从.Net到Java学习第四篇——spring boot+redis的全部內容,希望文章能夠幫你解決所遇到的問題。

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