1.Redis

一、 添加依赖

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

二、 配置文件:

application.properties文件中,可以参考多环境配置根据不同环境配置不同的库

#redis
spring.redis.host=localhost
spring.redis.port=6379
#spring.redis.password=123456
#spring.redis.database=0
#spring.redis.pool.max-active=8
#spring.redis.pool.max-idle=8
#spring.redis.pool.max-wait=-1
#spring.redis.pool.min-idle=0
#spring.redis.timeout=0

三、测试

主要涉及文件

component/DemoRedisComponent.java

package com.shuju.test2.component;

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.Component;

@Component
public class DemoRedisComponent {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public void set(String key, String value) {
        ValueOperations<String, String> ops = this.stringRedisTemplate.opsForValue();
        if (!this.stringRedisTemplate.hasKey(key)) {
            ops.set(key, value);
            System.out.println("set key success");
        } else {
            // 存在则打印之前的value值
            System.out.println("this key = " + ops.get(key));
        }
    }

    public String get(String key) {
        return this.stringRedisTemplate.opsForValue().get(key);
    }

    public void del(String key) {
        this.stringRedisTemplate.delete(key);
    }
}

测试类

package com.shuju.test2;

import com.shuju.test2.component.DemoRedisComponent;
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 Test2ApplicationTests {

    @Autowired
    private DemoRedisComponent demoRedisComponent;

    @Test
    public void set() {
        demoRedisComponent.set("demo", "hello world");
    }

    @Test
    public void get() {
        System.out.println(demoRedisComponent.get("demo"));
    }

    @Test
    public void del() {
        demoRedisComponent.del("demo");
    }

}

注:生产环境下,如果外网可以访问,一定要设置密码!

Last updated