從.Net到Java學習系列目錄html
「學習java已經十天,有時也懷念當初.net的經典,讓這語言將你我相連,懷念你......」接上一篇,本篇使用到的框架redis、FastJSON。java
環境準備redis
安裝redis,下圖是我本機的redis綠色版,你能夠網上自行下載安裝,若是不知道如何怎麼操做,能夠移步到個人另外一篇文章:ASP.NET Redis 開發
spring
以管理員身份打開CMD窗口:數據庫
C:\Users\zouqj>e: E:\>cd E:\Redis-x64-3.2.100 E:\Redis-x64-3.2.100>redis-server --service-install redis.windows.conf --loglevel verbose --service-name redis --port 6379
運行以後,記得啓動redis服務,我這裏redis沒有設置密碼。json
啓動服務命令:net start redissegmentfault
關於FastJSON框架的使用呢能夠參考文章:高性能JSON框架之FastJson的簡單使用windows
修改pom.xml,添加redis的依賴springboot
<!--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: 0
host: 127.0.0.1
port: 6379
pool:
max-active: 100
max-idle: 10
max-wait: 100000
timeout: 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註解大體處理流程就是:
一、先去掃描已經被@Component所註釋的類,固然會先判斷有沒有@Condition相關的註解。
二、而後遞歸的取掃描該類中的@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; } @Bean public 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 { @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; } }
因爲項目中引入了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(); @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"); } }
咱們發現,在單元測試類上面自動添加了2個註解,@SpringBootTest和@RunWith(SpringRunner.class)
@SpringBootTest註解是SpringBoot自1.4.0版本開始引入的一個用於測試的註解。
@RunWith就是一個運行器
@RunWith(SpringRunner.class)就是指用SpringRunner來運行
運行單元測試:
查看redis中的結果,這裏用到一個可視化的redis管理工具:RedisDesktopManager