從.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.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

最終配置如下:

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

全選所有方法

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

}
View Code

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

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

@RunWith就是一個運行器

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

運行單元測試:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM