Spring Boot(五)缓存(json格式)

1、建立新工程并编辑pom文件

<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>
	<groupId>com.github.ralgond</groupId>
	<artifactId>boot-redis</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.0.RELEASE</version>
	</parent>
	
	<properties>
		<start-class>com.github.ralgond.bootcache.BootCacheMainApp</start-class>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-cache</artifactId>
		</dependency>

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

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.0</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

2、工程结构

3、编辑application.yml

server:
  port: 8888
  
spring:
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379

4、编辑User类

package com.github.ralgond.bootcache.entity;

public class User {
	private Integer id;
    private String name;
    
	public User() {
	}
	public User(Integer id, String name) {
		this.id = id;
		this.name = name;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + "]";
	}
}

5、编辑UserService类

package com.github.ralgond.bootcache;

import java.util.HashMap;

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 org.springframework.stereotype.Service;

import com.github.ralgond.bootcache.entity.User;

@Service
@CacheConfig(cacheNames = "user")
public class UserService {
	
	HashMap<Integer, User> userMap = new HashMap<>();
	int maxUserId = 1;
	
	@CachePut(key = "#u.id")
	public synchronized User addUser(User u) {
		u.setId(maxUserId++);
		userMap.put(u.getId(), u);
		return u;
	}
	
	@Cacheable(key = "#id", unless="#result == null")
	public synchronized User getUser(int id) {
		User user = userMap.get(id);
		System.out.println("====>get from db: " + user);
		return user;
	}
	
	@CacheEvict(key = "#id")
	public synchronized void deleteUser(int id) {
		userMap.remove(id);
	}
}

6、编辑CacheConfig类

package com.github.ralgond.bootcache;

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

import org.springframework.cache.CacheManager;
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.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class CacheConfig {

	@Bean
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
		// 注入数据源
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 使用GenericJackson2JsonRedisSerializer 替换默认序列化
        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        // key-value结构序列化数据结构
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        // hash数据结构序列化方式,必须这样否则存hash 就是基于jdk序列化的
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        
        // 启用默认序列化方式
        redisTemplate.setEnableDefaultSerializer(true);
        redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer);

        /// redisTemplate.afterPropertiesSet();
        return redisTemplate;
	}
	
	@Bean
	public CacheManager cacheMananger(RedisTemplate redisTemplate) {
		RedisCacheConfiguration userCacheConf = RedisCacheConfiguration.defaultCacheConfig()
								.entryTtl(Duration.ofSeconds(30))
								.disableCachingNullValues()
							        .serializeValuesWith(
			RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()));
																		
		Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
		
		redisCacheConfigurationMap.put("user", userCacheConf);
		
		RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());
		
		RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig();
		defaultCacheConfig.entryTtl(Duration.ofSeconds(20));
		
		RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter, defaultCacheConfig, redisCacheConfigurationMap);
		
		return cacheManager;
		
	}
}

7、编辑主启动类

package com.github.ralgond.bootcache;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.github.ralgond.bootcache.entity.User;


@SpringBootApplication
@RestController
@EnableCaching
public class BootCacheMainApp {
	
	@Autowired
	UserService userService;
	
	@RequestMapping(method=RequestMethod.POST, value="/user/add/{name}")
	public User addUser(@PathVariable("name") String name) {
		User user = new User(-1, name);
		return userService.addUser(user);
	}
	
	@RequestMapping(method=RequestMethod.POST, value="/user/del/{id}")
	public void delUser(@PathVariable("id") int id) {
		userService.deleteUser(id);
	}
	
	@RequestMapping(method=RequestMethod.GET, value="/user/{id}")
	public User getUser(@PathVariable("id") int id) {
		User user = userService.getUser(id);
		return user;
	}
	
	public static void main(String args[]) {
		SpringApplication.run(BootCacheMainApp.class, args);
	}
}
posted @ 2020-12-23 16:07  ralgo  阅读(338)  评论(0编辑  收藏  举报