SpringBoot使用Redis緩衝

來源:互聯網
上載者:User

標籤:資料庫   raw   target   password   清空   mil   jar包   bin   app   

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

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

  (2)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

  (3)建立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@EnableCachingpublic 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);     }}

  (4)建立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,方法調用後將立即清除緩衝

  (5)service層與controller層跟上一篇整合一樣,啟動redis伺服器,redis伺服器的安裝與啟動可以參考之前的部落格,地址如下:

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

  (6)配置log4j日誌資訊,如下:

 

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

 

  

 

SpringBoot使用Redis緩衝

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.