天天看點

從.Net到Java學習第四篇——spring boot+redis

從.Net到Java學習系列目錄

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

環境準備

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

從.Net到Java學習第四篇——spring boot+redis
以管理者身份打開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沒有設定密碼。

啟動服務指令: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: 0
      host: 127.0.0.1
      port: 6379
      pool:
        max-active: 100
        max-idle: 10
        max-wait: 100000
      timeout: 0      

最終配置如下:

從.Net到Java學習第四篇——spring boot+redis

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

    @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,如下圖所示:

從.Net到Java學習第四篇——spring boot+redis

全選所有方法

從.Net到Java學習第四篇——spring boot+redis

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

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

從.Net到Java學習第四篇——spring boot+redis
從.Net到Java學習第四篇——spring boot+redis
@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");
    }

}      

View Code

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

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

@RunWith就是一個運作器

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

運作單元測試:

從.Net到Java學習第四篇——spring boot+redis

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

從.Net到Java學習第四篇——spring boot+redis
部落格位址: http://www.cnblogs.com/jiekzou/
部落格版權:

本文以學習、研究和分享為主,歡迎轉載,但必須在文章頁面明顯位置給出原文連接配接。

如果文中有不妥或者錯誤的地方還望高手的你指出,以免誤人子弟。如果覺得本文對你有所幫助不如【推薦】一下!如果你有更好的建議,不如留言一起讨論,共同進步!

再次感謝您耐心的讀完本篇文章。

其它:

.net-QQ群4:612347965

java-QQ群:805741535

H5-QQ群:773766020

我的拙作《ASP.NET MVC企業級實戰》《H5+移動應用實戰開發》

《Vue.js 2.x實踐指南》

《JavaScript實用教程 》

《Node+MongoDB+React 項目實戰開發》

已經出版,希望大家多多支援!