1 프로젝트 구성
- 응용 프로그램: springboot rest api
- 데이터베이스: mysql
- jdbc 프레임워크: jpa
- 캐시 미들웨어: redis
2 실행 springboot
-
2.1 공식 웹사이트에서 가장 기본적인 restful 애플리케이션 다운로드
완성된 제품을 직접 다운로드하고 git 명령을 찾습니다. git clone https://github.com/spring-guides/gs-rest-service.git
폴더를 만들고 여기에서 git bash를 엽니다(git 설치).
Idea에서 완제품 열기(전체 폴더)
-
2.2 애플리케이션 실행
gradle -> bootRun 오른쪽 클릭 -> 실행/Deubg
-
http://localhost:8080/greeting?name=lanxingisthebest를 통한 액세스
3 액세스 mysql
-
gradle 종속성 추가(jpa를 통해)
구현('mysql:mysql-connector-java')
구현('org.springframework.boot:spring-boot-starter-data-jpa') -
구성 파일 및 데이터베이스 구성 추가
application.yml 파일 생성
spring: datasource: url: jdbc:mysql://localhost:3306/user_info username: root password: root jpa: show-sql: true
-
클래스 조정
-
mysql은 데이터 조각을 삽입한 다음 http://localhost:8080/listAllUser를 통해 데이터베이스를 쿼리합니다.
4 레디스 캐시 설정
-
그래들 의존성 추가
구현('org.springframework.boot:spring-boot-starter-data-redis')
구현('org.springframework.boot:spring-boot-starter-cache') -
구성 파일 구성 redis 매개변수
spring: datasource: url: jdbc:mysql://localhost:3306/user_info username: root password: root jpa: show-sql: true ## Redis 配置 redis: ## Redis数据库索引(默认为0) database: 0 ## Redis服务器地址 host: localhost ## Redis服务器连接端口 port: 6379 ## Redis服务器连接密码(默认为空) password: jedis: pool: ## 连接池最大连接数(使用负值表示没有限制) #spring.redis.pool.max-active=8 max-active: 8 ## 连接池最大阻塞等待时间(使用负值表示没有限制) #spring.redis.pool.max-wait=-1 max-wait: -1 ## 连接池中的最大空闲连接 #spring.redis.pool.max-idle=8 max-idle: 8 ## 连接池中的最小空闲连接 #spring.redis.pool.min-idle=0 min-idle: 0 ## 连接超时时间(毫秒) timeout: 1200
-
Redis 구성 클래스
RedisConfig 코드package com.example.restservice.config; 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.cache.RedisCacheWriter; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.*; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import java.time.Duration; /** * @author lzh * create 2019-09-24-15:07 */ @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { /** * 选择redis作为默认缓存工具 * @param redisConnectionFactory * @return */ /*@Bean //springboot 1.xx public CacheManager cacheManager(RedisTemplate redisTemplate) { RedisCacheManager rcm = new RedisCacheManager(redisTemplate); return rcm; }*/ @Bean public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofHours(1)); // 设置缓存有效期一小时 return RedisCacheManager .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory)) .cacheDefaults(redisCacheConfiguration).build(); } /** * retemplate相关配置 * @param factory * @return */ @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); // 配置连接工厂 template.setConnectionFactory(factory); //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式) Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jacksonSeial.setObjectMapper(om); // 值采用json序列化 template.setValueSerializer(jacksonSeial); //使用StringRedisSerializer来序列化和反序列化redis的key值 template.setKeySerializer(new StringRedisSerializer()); // 设置hash key 和value序列化模式 template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(jacksonSeial); template.afterPropertiesSet(); return template; } /** * 对hash类型的数据操作 * * @param redisTemplate * @return */ @Bean public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForHash(); } /** * 对redis字符串类型数据操作 * * @param redisTemplate * @return */ @Bean public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForValue(); } /** * 对链表类型的数据操作 * * @param redisTemplate * @return */ @Bean public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForList(); } /** * 对无序集合类型的数据操作 * * @param redisTemplate * @return */ @Bean public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForSet(); } /** * 对有序集合类型的数据操作 * * @param redisTemplate * @return */ @Bean public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForZSet(); } }
-
코드는 @Cacheable을 통해 redis 캐시를 사용합니다.
-
인터페이스 접속 후 redis 도구를 통해 데이터 조회
redis-lic.exe
명령 키 *를 클릭합니다.