SpringBoot之整合Redis

一、SpringBoot整合单机版Redis

1、在pom.xml文件中加入redis的依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.3.5.RELEASE</version>
</dependency>

2、在application.properties文件中增加redis配置

#redis
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=111111

3、在入口类加入注解@EnableCaching注解,开始缓存

@SpringBootApplication
@EnableCaching
public class SpringbootmybatisApplication {

public static void main(String[] args) {
SpringApplication.run(SpringbootmybatisApplication.class, args);
}
}

4、在service实现层的方法上加入@Cacheable注解,意思是加入缓存

@Override
@Cacheable(value = "user.list")-----加入缓存,并且key为user.list
public List<User> findAll() {
System.out.println("进来了");
return userAtomMapper.finaAll();
}
当第一次访问的时候,会进入这个方法,然后会将结果存入缓存,第二次访问的时候,就不会进入这个方法,会直接从缓存中获取,这个缓存就是redis

二、SpringBoot整合集群Redis

1、在application.properties文件中增加redis的集群配置

#redis集群模式
spring.redis.cluster.nodes=127.0.0.1:5001,127.0.0.1:5002,127.0.0.1:5003,127.0.0.1:5004,127.0.0.1:5005,127.0.0.1:5006

2、编写RedisConfig.java

@Configuration
public class RedisConfig {
@Value("${spring.redis.cluster.nodes}")
private String redisNodes;
@Bean
public JedisCluster jedisCluster(){
String[] clusterNodes = redisNodes.split(",");
Set<HostAndPort> nodes = new HashSet<>();
for(String node:clusterNodes){
String[] hp = node.split(":");
nodes.add(new HostAndPort(hp[0],Integer.valueOf(hp[1])));
}
JedisCluster jedisCluster = new JedisCluster(nodes);
return jedisCluster;
}
}
①@Configuration注解意味着这个类是一个配置类,相当于之前的xml文件
②@Bean注解相当于之前的<bean/>
③使用注解 @Value("${spring.redis.cluster.nodes}"),可以获取再application.properties文件里的spring.redis.cluster.nodes的值
④编写jedisCluster构造方法的目的是为了获取集群的所有节点的服务器ip和端口

3、开始使用RedisCluster

@Service
public class UserServiceImpl implements UserService {

@Autowired
private JedisCluster jedisCluster;

@Override
public String findRedis() {
return jedisCluster.get("name");
}
}

4、测试

/**
* 从集群redis获取
* @return
*/
@RequestMapping(value = "findRedis",method = RequestMethod.GET)
public String findRedis(){
return userService.findRedis();
}
在浏览器输入localhost:8080/findRedis,看到如下结果,说明整合成功。














猜你喜欢

转载自www.cnblogs.com/rrb520/p/10265782.html