包括jedis,spring-data-redis以及jackson(在将对象序列化保存到redis中需要)
1.pom.xml
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-data-redisartifactId>
- dependency>
-
- <dependency>
- <groupId>redis.clientsgroupId>
- <artifactId>jedisartifactId>
- <version>3.3.0version>
- dependency>
2. application.properties
- # -------------------- redis config B -------------------------
- # Redis数据库索引(默认为0)
- spring.redis.database=0
- # Redis服务器地址
- spring.redis.host=192.168.0.24
- # Redis服务器连接端口
- spring.redis.port=6379
- # Redis服务器连接密码(默认为空)
- spring.redis.password=
- # 连接池最大连接数(使用负值表示没有限制)
- spring.redis.jedis.pool.max-active=100
- # 连接池最大阻塞等待时间(使用负值表示没有限制)
- spring.redis.jedis.pool.max-wait=-1ms
- # 连接池中的最大空闲连接
- spring.redis.jedis.pool.max-idle=10
- # 连接池中的最小空闲连接
- spring.redis.jedis.pool.min-idle=0
- # 连接超时时间(毫秒)
- spring.redis.jedis.timeout=1000
- # -------------------- redis config E -------------------------
3.在resources目录下建立readis.properties
- redis.host=localhost
- redis.port=6379
- redis.maxIdle=100
- redis.maxTotal=100
- redis.maxWaitMillis=6000
- redis.testOnBorroW=true
4.建立CacheConfig
- package com.huamei.sbdome01.config;
-
- import org.springframework.context.annotation.Bean;
- 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.GenericJackson2JsonRedisSerializer;
- import org.springframework.data.redis.serializer.StringRedisSerializer;
-
- public class CacheConfig {
-
- @Bean
- public RedisTemplate
- RedisTemplate
- redisTemplate.setConnectionFactory(cf);
-
- GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
-
- redisTemplate.setKeySerializer(new StringRedisSerializer());
- redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);
-
- redisTemplate.setHashKeySerializer(new StringRedisSerializer());
- redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);
- return redisTemplate;
- }
-
-
- @Bean
- public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
- StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
- stringRedisTemplate.setConnectionFactory(factory);
- return stringRedisTemplate;
- }
-
- }
这时候我们已经完成redis的集成了
下面我们在编写一个controller用于测试
- /**
- * 用于测试redis集成
- * @author Administrator
- * @create 2019-12-1822:16
- */
- @RestController
- public class RedisTestController {
-
- @Resource
- private RedisTemplate redisTemplate;
-
- @RequestMapping(value = "/redis")
- public Object redis() {
-
- String name = "redis test";
- redisTemplate.opsForValue().set("redisTest", name);
-
- Map
map = new HashMap<>(); - map.put("code", 1);
- map.put("msg", "操作成功");
-
- return map;
- }
-
- }