如何创建SpringBoot项目应该就不用讲了吧。不熟悉的,建议自己搜索哦。提示一下,在IDEA中直接使用Spring Initializr 创建项目一下子就可以搞定了。这里不做过多介绍。
整合Redis,第一步当然要导入他的依赖啦!
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-redis org.apache.commons commons-pool2
然后我们跟以前整合mysql一样,我们还需要配置他的相关内容。
spring:
redis:
#Redis的服务器地址(记得使用自己服务器的ip地址)
host: 119.91.153.74
#Redis的端口号
port: 6379
#数据库索引(选择几号数据库,默认有16个数据库)
database: 0
#连接超时(毫秒,180,000ms = 180s = 3min)
timeout: 1800000
lettuce:
pool:
#连接池最大连接数(负数表示不限制)
max-active: 20
#最大阻塞等待时间(负数表示不限制)
max-wait: -1
#连接池中最大空闲连接
max-idle: 5
#连接池中最小空闲连接
min-idle: 0
再然后,添加Redis的配置类。(这个比较简单,后续有遇到其它问题,需要在配置文件中加东西的话,可以再百度一下,并进行添加)
package com.example.redisdemo2.config;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(connectionFactory);
// 使用Jackson2JsonRedisSerializer来序列化/反序列化redis的value值
Jackson2JsonRedisSerializer
测试:
package com.example.redisdemo2.controller;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
public class RedisController {
@Resource
private RedisTemplate redisTemplate;
@GetMapping("/demo1")
public String testRedis(){
//添加数据
redisTemplate.opsForValue().set("name", "Tom");
//获取数据
String name = (String) redisTemplate.opsForValue().get("name");
return name;
}
}
结果:



