02_SpringBoot集成Redis

作者: 明天你好向前奔跑 | 来源:发表于2017-11-03 17:49 被阅读175次

@author Jacky wang

转载请注明出处,http://www.jianshu.com/p/4cfedabca746

看了网上一些Springboot集成Springboot的很多资料,发现对Redis的配置复杂了,自己总结了Springboot集成Redis的简单方式。

1. 创建Maven工程

搭建Springboot工程,包结构如下:

Springboot的标准包结构···
3.png

2. pom文件添加依赖,properties添加配置

pom.xml :
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.dream</groupId>
    <artifactId>spring-redis</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!-- Springboot集成Redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <!-- Springboot测试 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- 热部署插件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

-----------------------------------------------------------------------------------------------------

application.properties:(很多其实是默认的,这里全部列出来)
    #指定连接工厂使用的Database index,默认为: 0
    spring.redis.database=0
    #指定Redis server host,默认为: localhost
    spring.redis.host=127.0.0.1
    #指定Redis server的密码
    #spring.redis.password=
    #指定连接池最大的活跃连接数,-1表示无限,默认为8
    spring.redis.pool.max-active=8
    #指定连接池最大的空闲连接数,-1表示无限,默认为8
    spring.redis.pool.max-idle=8
    #指定当连接池耗尽时,新获取连接需要等待的最大时间,以毫秒单位,-1表示无限等待
    spring.redis.pool.max-wait=-1
    #指定连接池中空闲连接的最小数量,默认为0
    spring.redis.pool.min-idle=2
    #指定redis服务端端口,默认: 6379
    spring.redis.port=6379
    #指定redis server的名称
    #spring.redis.sentinel.master
    #指定sentinel节点,逗号分隔,格式为host:port.
    #spring.redis.sentinel.nodes
    #指定连接超时时间,毫秒单位,默认为0
    spring.redis.timeout=0

3. RedisTemplate的处理

/**
 * Redis数据库操作对象
 * @author wwj
 */
@Component
public class RedisServiceImpl {

    @Autowired
    private RedisTemplate redisTemplate;
    
    /**
     * 写入缓存
     * @param key
     * @param value
     * @return
     */
    
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * 写入缓存设置时效时间
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * 读取缓存
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }
    
    /**
     * 判断缓存中是否有对应的value
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }
    
    /**
     * 删除对应的value
     * @param key
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }
    
    /**
     * 批量删除对应的value
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * 批量删除key
     * @param pattern
     */
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0)
            redisTemplate.delete(keys);
    }

    /**
     * 哈希 添加
     * @param key
     * @param hashKey
     * @param value
     */
    public void hmSet(String key, Object hashKey, Object value){
        HashOperations<String, Object, Object>  hash = redisTemplate.opsForHash();
        hash.put(key,hashKey,value);
    }

    /**
     * 哈希获取数据
     * @param key
     * @param hashKey
     * @return
     */
    public Object hmGet(String key, Object hashKey){
        HashOperations<String, Object, Object>  hash = redisTemplate.opsForHash();
        return hash.get(key,hashKey);
    }

    /**
     * 列表添加
     * @param k
     * @param v
     */
    public void lPush(String k,Object v){
        ListOperations<String, Object> list = redisTemplate.opsForList();
        list.rightPush(k,v);
    }

    /**
     * 列表获取
     * @param k
     * @param l
     * @param l1
     * @return
     */
    public List<Object> lRange(String k, long l, long l1){
        ListOperations<String, Object> list = redisTemplate.opsForList();
        return list.range(k,l,l1);
    }

    /**
     * 集合添加
     * @param key
     * @param value
     */
    public void add(String key,Object value){
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        set.add(key,value);
    }

    /**
     * 集合获取
     * @param key
     * @return
     */
    public Set<Object> setMembers(String key){
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        return set.members(key);
    }

    /**
     * 有序集合添加
     * @param key
     * @param value
     * @param scoure
     */
    public void zAdd(String key,Object value,double scoure){
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        zset.add(key,value,scoure);
    }

    /**
     * 有序集合获取
     * @param key
     * @param scoure
     * @param scoure1
     * @return
     */
    public Set<Object> rangeByScore(String key,double scoure,double scoure1){
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        return zset.rangeByScore(key, scoure, scoure1);
    }
}

到这里就可以使用,RedisServiceImplRedis进行操作了,上面给出的方法比较全,可以选择需要用到的进行使用。

4. 测试

4.1 Application入口类
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
4.2 User实体类
为了测试,还提供了一个User实体类,因为产生了传输过程,因此这里必须要实现Serializable接口。
public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    private String username;
    private int age;

    public User() {
        super();
    }

    public User(String username, int age) {
        super();
        this.username = username;
        this.age = age;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User [username=" + username + ", age=" + age + "]";
    }
}
4.2 SpringbootRedisTest测试类
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)//指定springboot的启动类
public class SpringBootRedisTest {

    @Autowired
    private RedisServiceImpl redisService;
    
    @Test
    public void testSet() {
        String key = "keyTest";
        String val = "keyVal2";
        redisService.set(key, val);
        User user = new User("jack", 24);
        redisService.set("user", user);
    }
    
    @Test
    public void testGet() {
        String key = "keyTest";
        String key2 = "user";
        String val = (String)redisService.get(key);
        User user = (User)redisService.get(key2);
        System.err.println(val);
        System.err.println(user);
    }

    @Test
    public void testRemove() {
        String key = "keyTest";
        String key2 = "user";
        redisService.remove(key);
        redisService.remove(key2);
    }
    
    @Test
    public void testSetExpire() throws Exception {
        String key = "testExpire";
        String value = "hello";
        long expireTime = 60L;//60秒后消失
        redisService.set(key, value, expireTime);
    }
}

以上就是Springboot集成Redis的全部过程,实现起来是非常简单的。到这里总结一下:

1. 添加pom.xml : spring-boot-starter-data-redis的依赖
2. 配置application.properties
3. 对RedisTemplate进行部分功能的封装。

具体的测试结果就不贴出来了,这里贴一下testSetExpire()的结果。

1.png

相关文章

网友评论

    本文标题:02_SpringBoot集成Redis

    本文链接:https://www.haomeiwen.com/subject/kjztmxtx.html