zoukankan      html  css  js  c++  java
  • 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,看到如下结果,说明整合成功。














    
    
  • 相关阅读:
    Git SSH Key 生成步骤
    Mac终端(Terminal)自定义颜色,字体,背景
    MAC进入文件夹快捷键
    在Terminal中,如何打开Finder,并显示当前的目录
    mac文件夹怎么重命名?苹果电脑文件夹重命名快捷键
    如何在Mac OS X中开启或关闭显示隐藏文件命令
    怎样将二个路由进行桥接的方法
    关于apache access log 统计的那些事儿
    aaaa
    CodeForces463C Gargari and Bishops(贪心)
  • 原文地址:https://www.cnblogs.com/rrb520/p/10265782.html
Copyright © 2011-2022 走看看