加入pom.XML 依赖
<!--Redis-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置属性文件application.properties
#redis 单机版缓存
spring.redis.database=0
spring.redis.host=192.168.203.137
spring.redis.port=7000
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=1
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.min-idle=0
spring.redis.timeout=70000
主类上开启缓存注解
@SpringBootApplication(scanBasePackages = {"com.feifan"})
@EntityScan("com.feifan.entity")
@EnableJpaRepositories(basePackages = "com.feifan.dao")
@EnableCaching//开启缓存
public class Run extends SpringBootServletInitializer {
private static final Logger LOGGER = LoggerFactory.getLogger(Run.class);
public static void main(String[] args) {
LOGGER.info("马屁启动了呦");
Jedis jedis = new Jedis("192.168.203.137",7000);
jedis.set("hello","你是个呦");
System.err.println(jedis.get("hello")+jedis.get("name"));
SpringApplication.run(Run.class,args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Run.class);
}
}
测试类的实现:
实体类需要实现 序列化接口 :Serializable
@RequestMapping("get")
@ResponseBody
@Cacheable(value = "name")//开启缓存,键值为map 自定义
public Map<String, User> getSomeThing(){
System.err.println("第一次进来了呀");
Map<String,User> map = new HashMap<>();
User user = new User();
user.setAge(18);
user.setBrithday(new Date());
user.setCreateTime(new Date());
user.setGender("男");
map.put("one",user);
map.put("two",user);
return map;
}
整合redis 集群
#整合redis集群
spring.redis.cluster.nodes=192.168.203.137:7000,192.168.203.137:7001,192.168.203.137:7002,192.168.203.137:7003,192.168.203.137:7004,192.168.203.137:7005,192.168.203.137:7006,192.168.203.137:7007,192.168.203.137:7008
配置类:
//获取属性文件中的值
@Value("${spring.redis.cluster.nodes}")
private String redisNode;
@Bean
public JedisCluster getJedisCluster(){
//获取集群数据
Set<HostAndPort> nodes = new HashSet<>();
String [] hosts = redisNode.split(",");
for (String host:hosts)
{
String [] port = host.split(":");
HostAndPort hp = new HostAndPort(port[0],Integer.valueOf(port[1]));
nodes.add(hp);
}
JedisCluster jedisCluster = new JedisCluster(nodes);
return jedisCluster;
}
使用集群:
@Autowired
private JedisCluster jedisCluster;
jedisCluster.set("你看","你是哪个");