springboot 整合 redis

 pom.xml:

<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
<!--redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

application.properties:

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/hrms?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database=mysql
#自动建表
spring.jpa.hibernate.ddl-auto=update
#设置数据库方言
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
#打印sql
spring.jpa.show-sql=true

# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=123456
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1ms
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=200ms

springboot入口:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
*
*
*@author FastKing
*@date 17:42 2018/11/1
*@param 
**/
@SpringBootApplication
@EnableSwagger2
@EnableCaching
public class DemoApplication {

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

}

 @EnableCaching表示开启缓存

 redis配置类:

package com.example.demo.config.redis;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.RedisCacheConfiguration;
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.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;

/**
 * @author FastKing
 * @version 1.0
 * @date 2018/11/5 11:40
 **/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

	@Bean
	public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory){

		//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
		RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
		redisTemplate.setConnectionFactory(connectionFactory);
		Jackson2JsonRedisSerializer serializer  = new Jackson2JsonRedisSerializer(Object.class);
		ObjectMapper mapper = new ObjectMapper();
		mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
		serializer.setObjectMapper(mapper);
		redisTemplate.setValueSerializer(serializer);

		//使用StringRedisSerializer来序列化和反序列化redis的key值
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		redisTemplate.afterPropertiesSet();
		return redisTemplate;

	}

	@Bean
	public CacheManager cacheManager(RedisConnectionFactory connectionFactory){
		// 生成一个默认配置,通过config对象即可对缓存进行自定义配置
		// 不缓存空值
		RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().disableCachingNullValues();

		// 设置一个初始化的缓存空间set集合
		HashSet<String> cacheNames = new HashSet<>();
		cacheNames.add("timeGroup");
		cacheNames.add("user");

		// 对每个缓存空间应用不同的配置
		HashMap<String, RedisCacheConfiguration> configMap = new HashMap<>(2);
		// 设置缓存的默认过期时间,也是使用Duration设置
		configMap.put("timeGroup",config.entryTtl(Duration.ofMinutes(1)));
		configMap.put("user",config.entryTtl(Duration.ofMinutes(1)));

		// 使用自定义的缓存配置初始化一个cacheManager
		// 注意这两句的调用顺序,一定要先调用该方法设置初始化的缓存名,再初始化相关的配置
		return RedisCacheManager.builder(connectionFactory).initialCacheNames(cacheNames).withInitialCacheConfigurations(configMap).build();
	}

}

前端index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="userList">

</div>
</body>
<script type="text/javascript" src="/js/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
    var obj = window.document.location;
    var BASE_PATH = obj.href.substring(0, obj.href.indexOf(obj.pathname));
    //请求渲染模拟
    $.ajax({
        url: BASE_PATH + "/user/list",
        type: "get",
        success: function f(data) {
            $.each(data,function (index, data) {
                $("#userList").append(data.username + ":<button onclick='detail("+data.id+")'>查看</button>");
            })
        }
    }),
    function detail(id){
        $.ajax({
            url: BASE_PATH + "/user/detail/"+id,
            type: "get",
            success: function f(data) {
                console.log(data);
            }
        })
    }
</script>
</html>

后端Controller:

package com.example.demo.controller;

import com.example.demo.jpa.UserJpa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author Fast King
 * @Date 2018/11/1 21:58
 * @Version 1.0
 **/
@RestController
@RequestMapping("user")
public class UserController {

	@Autowired
	private UserJpa userJpa;

	@GetMapping("list")
	public Object list(){
		return userJpa.findAll();
	}

	@GetMapping("detail/{id}")
	@Cacheable(value = "user" , key = "#id" , condition = "#result eq null ")
	public Object detail(@PathVariable Integer id){
		return userJpa.findById(id);
	}


}

@Cacheable为spring中的缓存注解

        redis是个键值对数据库

        value为你在redis配置类中设置的缓存空间名称,key为redis的键,condition为执行下面方法的条件

        使用了该注解的方法,会优先从redis中找对应数据,如果redis中有则直接返回,如果没有再执行方法从数据库中找。

看一下效果:

我们点一下查看

 控制台打印了sql

再点查看,控制台就没有打印了。

过一分钟后,redis缓存失效,再点查看,控制台就又打印了

说明redis缓存成功

猜你喜欢

转载自blog.csdn.net/weixin_39841589/article/details/83753828