最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot使用Redis緩存的實(shí)現(xiàn)方法

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

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

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

 ?。?)修改項(xiàng)目啟動(dòng)類,增加注解@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數(shù)據(jù)庫(kù)索引(默認(rèn)為0)
spring.redis.database=0
# Redis服務(wù)器地址
spring.redis.host=172.31.19.222
# Redis服務(wù)器連接端口
spring.redis.port=6379
# Redis服務(wù)器連接密碼(默認(rèn)為空)
spring.redis.password=
# 連接池最大連接數(shù)(使用負(fù)值表示沒有限制)
spring.redis.pool.max-active=8
# 連接池最大阻塞等待時(shí)間(使用負(fù)值表示沒有限制)
spring.redis.pool.max-wait=-1
# 連接池中的最大空閑連接
spring.redis.pool.max-idle=8
# 連接池中的最小空閑連接
spring.redis.pool.min-idle=0
# 連接超時(shí)時(shí)間(毫秒)
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);
    //設(shè)置緩存過期時(shí)間 
    cacheManager.setDefaultExpiration(10000);
    return cacheManager;
  }
  @Bean
  public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory){
    StringRedisTemplate template = new StringRedisTemplate(factory);
    setSerializer(template);//設(shè)置序列化工具
    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,則方法調(diào)用后將立即清空所有緩存
  @CacheEvict(key ="#p0",allEntries=true)
  @Delete("delete from user where id=#{id}")
  void deleteById(@Param("id")String id);
}

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

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

  @CacheEvict,指定key,刪除緩存數(shù)據(jù),allEntries=true,方法調(diào)用后將立即清除緩存

  (6)service層與controller層跟上一篇整合一樣,啟動(dòng)redis服務(wù)器,redis服務(wù)器的安裝與啟動(dòng)可以參考之前的博客,地址如下:

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

 ?。?)配置log4j日志信息,如下:

## LOG4J配置
log4j.rootCategory=DEBUG,stdout
## 控制臺(tái)輸出
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

  ?。?)驗(yàn)證redis緩存

  首先我們向user表總插入一條數(shù)據(jù),數(shù)據(jù)庫(kù)顯示如下:

  現(xiàn)在,我們查詢一下user表中id=24的數(shù)據(jù),觀擦控制臺(tái)輸出的信息,如下:

  通過控制臺(tái)輸出信息我們可以知道,這次執(zhí)行了數(shù)據(jù)庫(kù)查詢,并開啟了Redis緩存查詢結(jié)果。接下來我們?cè)俅尾樵僽ser表中id=24的數(shù)據(jù),觀察控制臺(tái),如下:

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

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

總結(jié)

以上所述是小編給大家介紹的SpringBoot使用Redis緩存的實(shí)現(xiàn)方法,希望對(duì)大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!

相關(guān)文章

  • maven報(bào)錯(cuò):Failed to execute goal on project問題及解決

    maven報(bào)錯(cuò):Failed to execute goal on p

    這篇文章主要介紹了maven報(bào)錯(cuò):Failed to execute goal on project問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-04-04
  • Java藍(lán)橋杯實(shí)現(xiàn)線段和點(diǎn)

    Java藍(lán)橋杯實(shí)現(xiàn)線段和點(diǎn)

    本文主要介紹Java藍(lán)橋杯實(shí)現(xiàn)線段和點(diǎn)的內(nèi)容,感興趣的小伙伴可以參考下文
    2021-08-08
  • Java使用snmp協(xié)議實(shí)現(xiàn)采集服務(wù)器信息

    Java使用snmp協(xié)議實(shí)現(xiàn)采集服務(wù)器信息

    SNMP是一種用于管理網(wǎng)絡(luò)設(shè)備的協(xié)議,它是一種標(biāo)準(zhǔn)化的協(xié)議,被用于監(jiān)控和管理網(wǎng)絡(luò)設(shè)備,這篇文章主要介紹了Java如何使用snmp協(xié)議采集服務(wù)器信息,需要的可以參考下
    2024-12-12
  • java線程池ThreadPoolExecutor類使用小結(jié)

    java線程池ThreadPoolExecutor類使用小結(jié)

    這篇文章主要介紹了java線程池ThreadPoolExecutor類使用,本文主要對(duì)ThreadPoolExecutor的使用方法進(jìn)行一個(gè)詳細(xì)的概述,示例代碼介紹了ThreadPoolExecutor的構(gòu)造函數(shù)的相關(guān)知識(shí),感興趣的朋友一起看看吧
    2022-03-03
  • 基于Java內(nèi)存溢出的解決方法詳解

    基于Java內(nèi)存溢出的解決方法詳解

    本篇文章是對(duì)Java內(nèi)存溢出的解決方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
    2013-05-05
  • Java讀取傳輸FTP文件實(shí)現(xiàn)示例

    Java讀取傳輸FTP文件實(shí)現(xiàn)示例

    本文主要介紹了Java讀取傳輸FTP文件方案,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-04-04
  • 解決 java.lang.NoSuchMethodError的錯(cuò)誤

    解決 java.lang.NoSuchMethodError的錯(cuò)誤

    這篇文章主要介紹了解決 java.lang.NoSuchMethodError的錯(cuò)誤的相關(guān)資料,需要的朋友可以參考下
    2017-06-06
  • springboot操作靜態(tài)資源文件的方法

    springboot操作靜態(tài)資源文件的方法

    這篇文章主要介紹了springboot操作靜態(tài)資源文件的方法,本文給大家提到了兩種方法,小編在這里比較推薦第一種方法,具體內(nèi)容詳情大家跟隨腳本之家小編一起看看吧
    2018-07-07
  • spring boot加載freemarker模板路徑的方法

    spring boot加載freemarker模板路徑的方法

    這篇文章主要介紹了spring boot加載freemarker模板路徑的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-11-11
  • java?Comparable和Comparator的區(qū)別及作用面試精講

    java?Comparable和Comparator的區(qū)別及作用面試精講

    這篇文章主要為大家介紹了java?Comparable和Comparator的區(qū)別及作用面試精講,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-10-10

最新評(píng)論

海盐县| 宝清县| 菏泽市| 云南省| 孝昌县| 潞城市| 璧山县| 长丰县| 百色市| 娱乐| 山东省| 威海市| 鞍山市| 九江县| 光山县| 武汉市| 宁乡县| 大足县| 南平市| 金坛市| 西乌珠穆沁旗| 桃园县| 元氏县| 连山| 天津市| 合水县| 谢通门县| 石泉县| 巫溪县| 海伦市| 乐业县| 乌拉特后旗| 濮阳市| 改则县| 长宁区| 平乐县| 大同市| 古蔺县| 米脂县| 上虞市| 乐业县|