《微服务之SpringBoot整合Redis》

前言:

       Redis是一个开源的、先进的key-value存储系统,可用于构建高性能的存储系统。Redis之处数据结构有字符串、哈希、列表、集合、排序集合、位图、超文本等。NoSQL(Not Only SQL)泛指非关系型的数据库。Redis是一种NoSQL,Redis具有读写非常快速、支持丰富的数据类型,所有的操作都是原子的等优点。

正文:

   一。新建SpringBoot工程---hello-redis

        在工程的pom文件中引入redis的起步依赖spring-boot-starter-redis

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

   二。配置Redis的数据源 ---application.yml

spring:
  redis:
    host: //redis访问IP
    port: //redis访问端口
    password:
    database: 1
    pool:
    jedis:
      pool:
        max-active: 8
        max-wait: -1ms  #需要注意下这里的写法
        max-idle: 500

   三。创建RedisDao层 

       该类通过@Repository来注入Spring IoC容器,通过RedisTemplate访问Redis,通过注入StringRedisTemplate的Bean

来对Redis数据库中的字符串类型的数据进行操作 

package com.redis.helloredis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import java.util.concurrent.TimeUnit;

@Repository
public class RedisDao {
    @Autowired
    private StringRedisTemplate template;
    public void setKey(String key, String value){
        ValueOperations<String, String> ops = template.opsForValue();
        ops.set(key,value, 1, TimeUnit.MINUTES);//1分钟过期
    }
    public String getValue(String key){
        ValueOperations<String, String> ops = this.template.opsForValue();
        return ops.get(key);
    }
}

   四。编写测试类 

扫描二维码关注公众号,回复: 2818189 查看本文章

        首先通过RedisDao向Redis设置两组字符串值,然后分别通过RedisDao从Redis中读取这两个值:

package com.redis.helloredis;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloRedisApplicationTests {

    @Test
    public void contextLoads() {
    }

    @Autowired
    RedisDao redisDao;
    @Test
    public void testRedis(){
        redisDao.setKey("name", "forezp");
        redisDao.setKey("age", "17");
        System.out.println(redisDao.getValue("name"));
        System.out.println(redisDao.getValue("age"));
    }

}

       启动单元测试,控制台打印出forezp和17两个字符串值,说明通过RedisDao首先向Redis数据库中写入了两个数据,然后又读取了这两个数据。

结语:

        用自己的实力,索要自己的未来。

猜你喜欢

转载自blog.csdn.net/yxf15732625262/article/details/81745236