欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot使用Redis緩存的實現方法

 更新時間:2018年02月04日 14:12:56   作者:gdpuzxs  
這篇文章主要介紹了SpringBoot使用Redis緩存的實現方法,需要的朋友可以參考下

(1)pom.xml引入jar包,如下:

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

 ?。?)修改項目啟動類,增加注解@EnableCaching,開啟緩存功能,如下:

package springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
@EnableCaching
public class SpringbootApplication{
  public static void main(String[] args) {
    SpringApplication.run(SpringbootApplication.class, args);
  }
}

 ?。?)application.properties中配置Redis連接信息,如下:

# Redis數據庫索引(默認為0)
spring.redis.database=0
# Redis服務器地址
spring.redis.host=172.31.19.222
# Redis服務器連接端口
spring.redis.port=6379
# Redis服務器連接密碼(默認為空)
spring.redis.password=
# 連接池最大連接數(使用負值表示沒有限制)
spring.redis.pool.max-active=8
# 連接池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.pool.max-wait=-1
# 連接池中的最大空閑連接
spring.redis.pool.max-idle=8
# 連接池中的最小空閑連接
spring.redis.pool.min-idle=0
# 連接超時時間(毫秒)
spring.redis.timeout=0

 ?。?)新建Redis緩存配置類RedisConfig,如下:

package springboot.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
 * Redis緩存配置類
 * @author szekinwin
 *
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
  @Value("${spring.redis.host}")
  private String host;
  @Value("${spring.redis.port}")
  private int port;
  @Value("${spring.redis.timeout}")
  private int timeout;
  //自定義緩存key生成策略
//  @Bean
//  public KeyGenerator keyGenerator() {
//    return new KeyGenerator(){
//      @Override
//      public Object generate(Object target, java.lang.reflect.Method method, Object... params) {
//        StringBuffer sb = new StringBuffer();
//        sb.append(target.getClass().getName());
//        sb.append(method.getName());
//        for(Object obj:params){
//          sb.append(obj.toString());
//        }
//        return sb.toString();
//      }
//    };
//  }
  //緩存管理器
  @Bean 
  public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
    RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
    //設置緩存過期時間 
    cacheManager.setDefaultExpiration(10000);
    return cacheManager;
  }
  @Bean
  public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory){
    StringRedisTemplate template = new StringRedisTemplate(factory);
    setSerializer(template);//設置序列化工具
    template.afterPropertiesSet();
    return template;
  }
   private void setSerializer(StringRedisTemplate template){
      @SuppressWarnings({ "rawtypes", "unchecked" })
      Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
      ObjectMapper om = new ObjectMapper();
      om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
      om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
      jackson2JsonRedisSerializer.setObjectMapper(om);
      template.setValueSerializer(jackson2JsonRedisSerializer);
   }
}

 ?。?)新建UserMapper,如下:

package springboot.dao;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import springboot.domain.User;
@Mapper
@CacheConfig(cacheNames = "users")
public interface UserMapper {
  @Insert("insert into user(name,age) values(#{name},#{age})")
  int addUser(@Param("name")String name,@Param("age")String age);
  @Select("select * from user where id =#{id}")
  @Cacheable(key ="#p0") 
  User findById(@Param("id") String id);
  @CachePut(key = "#p0")
  @Update("update user set name=#{name} where id=#{id}")
  void updataById(@Param("id")String id,@Param("name")String name);
  //如果指定為 true,則方法調用后將立即清空所有緩存
  @CacheEvict(key ="#p0",allEntries=true)
  @Delete("delete from user where id=#{id}")
  void deleteById(@Param("id")String id);
}

  @Cacheable將查詢結果緩存到redis中,(key="#p0")指定傳入的第一個參數作為redis的key。

  @CachePut,指定key,將更新的結果同步到redis中

  @CacheEvict,指定key,刪除緩存數據,allEntries=true,方法調用后將立即清除緩存

 ?。?)service層與controller層跟上一篇整合一樣,啟動redis服務器,redis服務器的安裝與啟動可以參考之前的博客,地址如下:

    http://www.cnblogs.com/gdpuzxs/p/6623171.html

  (7)配置log4j日志信息,如下:

## LOG4J配置
log4j.rootCategory=DEBUG,stdout
## 控制臺輸出
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n

  ?。?)驗證redis緩存

  首先我們向user表總插入一條數據,數據庫顯示如下:

  現在,我們查詢一下user表中id=24的數據,觀擦控制臺輸出的信息,如下:

  通過控制臺輸出信息我們可以知道,這次執(zhí)行了數據庫查詢,并開啟了Redis緩存查詢結果。接下來我們再次查詢user表中id=24的數據,觀察控制臺,如下:

  通過控制臺輸出信息我們可以知道,這次并沒有執(zhí)行數據庫查詢,而是從Redis緩存中查詢,并返回查詢結果。我們查看redis中的信息,如下:

  方法finduser方法使用了注解@Cacheable(key="#p0"),即將id作為redis中的key值。當我們更新數據的時候,應該使用@CachePut(key="#p0")進行緩存數據的更新,否則將查詢到臟數據。

總結

以上所述是小編給大家介紹的SpringBoot使用Redis緩存的實現方法,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!

相關文章

  • MyBatis Log Free插件IDE下載與使用方式

    MyBatis Log Free插件IDE下載與使用方式

    這篇文章主要介紹了MyBatis Log Free插件IDE下載與使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-07-07
  • Java中的HashMap源碼分析

    Java中的HashMap源碼分析

    這篇文章主要介紹了Java中的HashMap源碼分析,散列表是根據關鍵碼值(Key?value)而直接進行訪問的數據結構,也就是說,它通過把關鍵碼值映射到表中一個位置來訪問記錄,以加快查找的速度,這個映射函數叫做散列函數,存放記錄的數組叫做散列表,需要的朋友可以參考下
    2023-09-09
  • 淺談DetachedCriteria和Criteria的使用方法(必看)

    淺談DetachedCriteria和Criteria的使用方法(必看)

    下面小編就為大家?guī)硪黄獪\談DetachedCriteria和Criteria的使用方法(必看)。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-05-05
  • dubbo服務注冊到nacos的過程剖析

    dubbo服務注冊到nacos的過程剖析

    這篇文章主要為大家介紹了dubbo服務注冊到nacos的過程剖析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職極限
    2022-02-02
  • Spring @Profile注解詳解

    Spring @Profile注解詳解

    這篇文章主要介紹了Spring @Profile注解詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-08-08
  • java實現構造無限層級樹形菜單

    java實現構造無限層級樹形菜單

    這篇文章主要介紹了java實現構造無限層級樹形菜單,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-09-09
  • 多線程下怎樣保證OkHttpClient的線程安全

    多線程下怎樣保證OkHttpClient的線程安全

    這篇文章主要介紹了多線程下怎樣保證OkHttpClient的線程安全問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • HashMap原理的深入理解

    HashMap原理的深入理解

    這篇文章主要介紹了對HashMap原理的理解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-04-04
  • Spring Boot Shiro在Web應用中的作用詳解

    Spring Boot Shiro在Web應用中的作用詳解

    這篇文章主要為大家介紹了Spring Boot Shiro在Web應用中的作用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-02-02
  • SpringBoot項目打jar包與war包的詳細步驟

    SpringBoot項目打jar包與war包的詳細步驟

    SpringBoot和我們之前學習的web應用程序不一樣,其本質上是一個 Java應用程序,那么又如何部署呢?這篇文章主要給大家介紹了關于SpringBoot項目打jar包與war包的詳細步驟,需要的朋友可以參考下
    2023-02-02

最新評論