spring boot 中使用redis的簡單方法

1、首先要用Docker將redis啓動起來,使用默認端口號即可。

2、在pom文件中導入依賴

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.miller</groupId>
    <artifactId>fan-redis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>fan-redis</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

3、配置一下,將RedisTemplate交給spring容器管理

/**
 * @program: fan-redis
 * @description: Redis配置類
 * @author: Miller.FAN
 * @create: 2019-11-21 09:52
 **/
@Configuration
@ComponentScan
public class RedisConfig {
    //配置模板
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory cf) {
         RedisTemplate<String,Object> redis = new RedisTemplate<>();
        redis.setConnectionFactory(cf);
        return redis;
    }
}

4、在業務代碼中使用

import com.miller.fanredis.dao.Text;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @program: fan-redis
 * @description: 操作Service 將數據放在緩存中
 * @author: Miller.FAN
 * @create: 2019-11-21 10:10
 **/
@Service
public class RedisService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    //增加文本
    public HashMap<String,Object> addText(Text text) {
        HashMap<String,Object> ret = new HashMap<>();
        //redisTemplate.opsForValue().set("text_" + text.getId(),text);  //不設置過期時間
        if(true) { //設置過期時間 10小時後過期
            redisTemplate.opsForValue().set("text_" + text.getId(),text,10, TimeUnit.HOURS);
        }
        ret.put("OK","添加成功");
        return ret;
    }

    //query text
    public HashMap<String,Object> queryText(int id) {
        HashMap<String,Object> ret = new HashMap<>();
        ret.put("OK",redisTemplate.opsForValue().get("text_" + id));
        return ret;
    }
    //delete text
    public HashMap<String,Object> deleteText(int id) {
        HashMap<String,Object> ret = new HashMap<>();
        ret.put("OK",redisTemplate.delete("text_" + id));
        return ret;
    }
}

5、總結:正常情況下不會這樣實現,這裏只是爲了方便演示RedisTemplate提供的常用方法將數據存入緩衝,從緩衝中拿數據的方法。一般來說RedisTemplate與spring data Jpa配合使用。在查詢數據時先從緩衝中獲取,沒有時再用spring data Jpa的方法。

6、代碼和項目地址:https://github.com/XianbeiEmperor/fan-redis

 

//直接使用spring cache,只要掌握3個註解@EnableCaching 、@Cacheable 、@CacheEvict, 這個有個缺點:不能設置過期時間。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class SpringCacheTestApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringCacheTestApplication.class, args);
    }

}
/**
 * @program: spring-cache-test
 * @description: ss
 * @author: Miller.FAN
 * @create: 2019-11-22 13:23
 **/

import com.miller.fancache.springcachetest.dao.Test;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;


@Service
public class TestService {

    public void addText(Test test) {
        //向數據庫中寫
    }
    @Cacheable(value = "test", key = "#id")
    public void query(int id) {
        //優先級是查找先到緩存,找不到再到數據庫,並且存到緩存
    }

    @CacheEvict(value = "test", key = "test.getId()")
    public void update(Test test) {

    }

    @CacheEvict(value = "test", key = "#id")
    public void delete(int id) {

    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章