QQ图片20190403153546.jpgQQ图片20190403153551.jpg

1.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 http://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.0.4.RELEASE</version>

<relativePath/> <!-- lookup parent from repository -->

</parent>

<groupId>com.huinongtx</groupId>

<artifactId>springcache</artifactId>

<version>0.0.1-SNAPSHOT</version>

<name>springcache</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-jpa</artifactId>

</dependency>

<dependency>

<groupId>com.google.guava</groupId>

<artifactId>guava</artifactId>

<version>19.0</version>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-cache</artifactId>

</dependency>

<!-- spring boot 配置 -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-redis</artifactId>

</dependency>

<dependency>

<groupId>org.apache.commons</groupId>

<artifactId>commons-pool2</artifactId>

</dependency>

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>6.0.5</version>

</dependency>

<dependency>

<groupId>javax.xml.bind</groupId>

<artifactId>jaxb-api</artifactId>

<version>2.3.0</version>

</dependency>

<dependency>

<groupId>org.projectlombok</groupId>

<artifactId>lombok</artifactId>

<version>1.16.20</version>

<scope>provided</scope>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

</dependencies>

<build>

<plugins>

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

</plugins>

</build>

</project>

2.application.properties属性配置文件

spring.redis.host=localhost

spring.redis.port=6379

spring.redis.password=

spring.redis.lettuce.pool.max-active=7 

spring.redis.lettuce.pool.max-idle=7

spring.redis.lettuce.pool.min-idle=2

spring.redis.lettuce.pool.max-wait=-1ms

spring.redis.lettuce.shutdown-timeout=200ms

spring.cache.redis.cache-null-values=false

spring.cache.redis.time-to-live=600000

spring.cache.redis.use-key-prefix=true

spring.cache.type=redis

spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&characterEncoding=utf-8

spring.datasource.username=root

spring.datasource.password=

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.hikari.connection-timeout=20000

spring.datasource.hikari.minimum-idle=5

spring.datasource.hikari.maximum-pool-size=12

spring.datasource.hikari.idle-timeout=300000

spring.datasource.hikari.max-lifetime=1200000

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect

spring.jpa.properties.hibernate.id.new_generator_mappings=false

spring.jpa.properties.hibernate.format_sql=true

3.RedisConfig类

包名:com.huinongtx.springcache.config

类名:RedisConfig

类内容:

package com.huinongtx.springcache.config;

import org.springframework.beans.factory.annotation.Autowired;

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.core.env.Environment;

import org.springframework.data.redis.cache.RedisCacheConfiguration;

import org.springframework.data.redis.cache.RedisCacheManager;

import org.springframework.data.redis.connection.RedisPassword;

import org.springframework.data.redis.connection.RedisStandaloneConfiguration;

import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;

import java.time.Duration;

/**

* Created by dengdashuai on 2018/12/17.

*/

@Configuration

@EnableCaching

public class RedisConfig extends CachingConfigurerSupport {

    @Autowired

    private Environment environment;

    @Bean

    public LettuceConnectionFactory redisConnectionFactory(){

        RedisStandaloneConfiguration redisConf = new RedisStandaloneConfiguration();

        redisConf.setHostName(environment.getProperty("spring.redis.host"));

        redisConf.setPort(Integer.parseInt(environment.getProperty("spring.redis.port")));

        redisConf.setPassword(RedisPassword.of(environment.getProperty("spring.redis.password")));

        return new LettuceConnectionFactory(redisConf);

    }

    @Bean

    public RedisCacheConfiguration cacheConfiguration(){

        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()

                .entryTtl(Duration.ofSeconds(600))

                .disableCachingNullValues();

        return cacheConfiguration;

    }

    @Bean

    public RedisCacheManager cacheManager(){

        RedisCacheManager redisCacheManager = RedisCacheManager.builder(redisConnectionFactory())

                .cacheDefaults(cacheConfiguration())

                .transactionAware()

                .build();

        return redisCacheManager;

    }

}

4.实体类定义

包名:com.huinongtx.springcache.domain;

类名:Article

类内容:

package com.huinongtx.springcache.domain;

import lombok.AllArgsConstructor;

import lombok.Data;

import lombok.NoArgsConstructor;

import javax.persistence.*;

import java.io.Serializable;

/**

* Created by dengdashuai on 2018/12/18.

*/

@Entity

@Table(name="articles")

@Data

@NoArgsConstructor

@AllArgsConstructor

public class Article implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id

    @GeneratedValue(strategy=GenerationType.AUTO)

    @Column(name="article_id")

    private long articleId;

    @Column(name="title")

    private String title;

    @Column(name="category")

    private String category;

}

5.持久层repository接口

包名:com.huinongtx.springcache.repository

接口名:ArticleRepository

接口内容:

package com.huinongtx.springcache.repository;

import com.huinongtx.springcache.domain.Article;

import org.springframework.data.repository.CrudRepository;

/**

* Created by dengdashuai on 2018/12/18.

*/

public interface ArticleRepository extends CrudRepository<Article,Long> {

}

6.业务层service接口

包名:

接口名:

接口内容:

package com.huinongtx.springcache.service;

import com.huinongtx.springcache.domain.Article;

import java.util.List;

/**

* Created by dengdashuai on 2018/12/18.

*/

public interface IArticleService {

    List<Article> getAllArticles();

    Article getArticleById(long articleId);

    Article addArticle(Article article);

    Article updateArticle(Article article);

    void deleteArticle(long articleId);

}

7.业务层service接口的实现类

包名:com.huinongtx.springcache.service.impl;

类名:ArticleService

类内容:

package com.huinongtx.springcache.service.impl;

import com.huinongtx.springcache.domain.Article;

import com.huinongtx.springcache.repository.ArticleRepository;

import com.huinongtx.springcache.service.IArticleService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cache.annotation.CacheEvict;

import org.springframework.cache.annotation.CachePut;

import org.springframework.cache.annotation.Cacheable;

import org.springframework.cache.annotation.Caching;

import org.springframework.stereotype.Service;

import java.util.ArrayList;

import java.util.List;

/**

* Created by dengdashuai on 2018/12/18.

*/

@Service

public class ArticleService implements IArticleService {

    @Autowired

    private ArticleRepository articleRepository;

    @Override

    @Cacheable(value= "allArticlesCache", unless= "#result.size() == 0")

    public List<Article> getAllArticles() {

        System.out.println("--- Inside getAllArticles() ---");

        List<Article> list = new ArrayList<>();

        articleRepository.findAll().forEach(e -> list.add(e));

        return list;

    }

    @Override

    @Cacheable(value= "articleCache", key= "#articleId")

    public Article getArticleById(long articleId) {

        System.out.println("--- Inside getArticleById() ---");

        return articleRepository.findById(articleId).get();

    }

    @Override

    @Caching(

            put= { @CachePut(value= "articleCache", key= "#article.articleId") },

            evict= { @CacheEvict(value= "allArticlesCache", allEntries= true) }

    )

    public Article addArticle(Article article) {

        System.out.println("--- Inside addArticle() ---");

        return articleRepository.save(article);

    }

    @Override

    @Caching(

            put= { @CachePut(value= "articleCache", key= "#article.articleId") },

            evict= { @CacheEvict(value= "allArticlesCache", allEntries= true) }

    )

    public Article updateArticle(Article article) {

        System.out.println("--- Inside updateArticle() ---");

        return articleRepository.save(article);

    }

    @Override

    @Caching(

            evict= {

                    @CacheEvict(value= "articleCache", key= "#articleId"),

                    @CacheEvict(value= "allArticlesCache", allEntries= true)

            }

    )

    public void deleteArticle(long articleId) {

        System.out.println("--- Inside deleteArticle() ---");

        articleRepository.delete(articleRepository.findById(articleId).get());

    }

}

8.控制器

包名:com.huinongtx.springcache.controller

类名:ArticleController

类内容:

package com.huinongtx.springcache.controller;

import com.huinongtx.springcache.domain.Article;

import com.huinongtx.springcache.service.IArticleService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.HttpHeaders;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.*;

import org.springframework.web.util.UriComponentsBuilder;

import java.util.List;

/**

* Created by dengdashuai on 2018/12/18.

*/

@RestController

@RequestMapping("user")

public class ArticleController {

    @Autowired

    private IArticleService articleService;

    @GetMapping("article/{id}")

    public ResponseEntity<Article> getArticleById(@PathVariable("id") Long id) {

        Article article = articleService.getArticleById(id);

        return new ResponseEntity<Article>(article, HttpStatus.OK);

    }

    @GetMapping("articles")

    public ResponseEntity<List<Article>> getAllArticles() {

        List<Article> list = articleService.getAllArticles();

        return new ResponseEntity<List<Article>>(list, HttpStatus.OK);

    }

    @PostMapping("article")

    public ResponseEntity<Void> addArticle(@RequestBody Article article, UriComponentsBuilder builder) {

        Article savedArticle = articleService.addArticle(article);

        HttpHeaders headers = new HttpHeaders();

        headers.setLocation(builder.path("/article/{id}").buildAndExpand(savedArticle.getArticleId()).toUri());

        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);

    }

    @PutMapping("article")

    public ResponseEntity<Article> updateArticle(@RequestBody Article article) {

        articleService.updateArticle(article);

        return new ResponseEntity<Article>(article, HttpStatus.OK);

    }

    @DeleteMapping("article/{id}")

    public ResponseEntity<Void> deleteArticle(@PathVariable("id") Long id) {

        articleService.deleteArticle(id);

        return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);

    }

}