1. 程式人生 > >spring boot集成redis緩存

spring boot集成redis緩存

time pom find pre idle empty cep wait 參數

spring boot項目中使用redis作為緩存。

先創建spring boot的maven工程,在pom.xml中添加依賴

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>1.5.3.RELEASE</version>
        </dependency
> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <version>1.3.8.RELEASE</version> </dependency>

在application.properties中添加配置

server.port:9000        #服務啟動的端口
spring.redis.database
=0    #redis數據庫的索引,默認為0 spring.redis.host=192.168.133.130 #spring.redis.password= spring.redis.port=6379 spring.redis.pool.max-idle=8  #最大空閑鏈接數 spring.redis.pool.min-idle=0  #最小空閑連接數 spring.redis.pool.max-active=8 #連接池最大連接數,負數表示無最大連接數 spring.redis.pool.max-wait=-1  #連接池最大阻塞等待時間,負數表示沒有 #spring.redis.sentinel.master
= #主節點 #spring.redis.sentinel.nodes= #
spring.data.mongodb.host=192.168.133.130
spring.data.mongodb.port=27017
spring.data.mongodb.database=fzk

在啟動類中添加註解


@SpringBootApplication
@EnableCaching
public class Main {

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

@EnableCaching會為每個bean中被 @Cacheable, @CachePut and @CacheEvict修飾的public方法進行緩存操作。

緩存的用法

    @Cacheable(value = "test", key = "‘user_‘.concat(#root.args[0])")
    public User getUser(String userId) {
        System.out.println("in getUser");
        User user = new User();
        user.setId(userId);
        user.setPassword("passwd");
        user.setUsername("username");

        return user;
    }

這個方法在userId相同形同的情況下,第一次調用的時候會執行方法,以後每次在調用的時候會讀取緩存中的數據。

緩存的註解介紹:
@Cacheable
這個註解,會每次先檢查是否執行過這個方法,在從緩存數據庫中查看key是否相等,如果找到了,從緩存中讀取,沒有匹配的那麽執行該方法,將結果緩存。
緩存都是通過key-value進行儲存的,value或cacheNames必須指定(value是cacheNames的別名),指定多個value用(value = {"value1", "value2"})如果沒有指定key,spring會提供一個默認的KeyGenerator,這個KeyGenerator根據參數生成key,如果方法沒有參數返回KeyGenerator.EMPTY,如果有一個參數返回這個實例,如果有多個參數返回包含這些參數的SimpleKey。可以通過繼承CachingConfigurerSupport自己指定KeyGenerator,[email protected]定key,需要了解SPEL表達式。
多線程的情況下,可能同時會有多個線程同時進入一個沒被緩存過的方法,這樣會導致多個線程都會執行一遍方法,sync="true"會將第一次計算返回值的這個方法lock,計算完成後將結果緩存

@Cacheable(value="foos", sync="true")
public Foo executeExpensiveOperation(String id) {...}

在某些情況下,可能並不想把結果進行緩存,可通過condition進行篩選

@Cacheable(value="book", condition="#name.length() < 32")
public Book findBook(String name)

上面的#root表示的是返回值,其他一些可用的參數(來自spring官網)

技術分享

@CachePut
每次都會執行該方法,[email protected]

@CacheEvict
用於將清空緩存,可以指定key, value, condition,這幾個的用法與上面介紹的一致。key和condition可以為空,如果為空,表示用默認策略。

@CacheEvict(value="books", allEntries=true, beforeInvocation=true)
public void loadBooks(InputStream batch)

allEntries=true表示清空books下的所有緩存,默認為false,beforeInvocation=true表示是否在方法執行前就清空緩存,默認為false。

@Caching
可以包含上面介紹的三個註解,key-value分別對應(cachable=[@Cacheable], put=[@CachePut], evict=[@CacheEvict])

@Caching(evict = { @CacheEvict("primary"), @CacheEvict(cacheNames="secondary", key="#p0") })
public Book importBooks(String deposit, Date date)

@CacheConfig
是一個類級的註解

@CacheConfig("books")
public class BookRepositoryImpl implements BookRepository {

    @Cacheable
    public Book findBook(ISBN isbn) {...}
}

這樣類下的每個方法的緩存都用的是books,還可以指定自定義的KeyGenerator和CacheManager。

自定義緩存註解
通過使用上面的註解作為元直接實現自定義註解

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Cacheable(value="books", key="#isbn")
public @interface SlowService {
}

[email protected]

@SlowService
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)

與下面的註解功能相同

@Cacheable(cacheNames="books", key="#isbn")
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)

spring boot集成redis緩存