• springboot之redis


    1、pom.xml文件添加依赖

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

    2、yml文件添加redis

    #默认使用配置
    spring:
      profiles:
        active: @activatedProperties@
      redis:
        host: 127.0.0.1
        port: 6379
        password:
        lettuce:
          pool:
            max-active: 100
            max-idle: 10
            max-wait: 100000

    3、添加配置文件RedisConfig.java

    import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.core.StringRedisTemplate;
    import redis.clients.jedis.JedisPoolConfig;
    
    @Configuration
    @EnableAutoConfiguration
    public class RedisConfig {
    
        @Bean
        @ConfigurationProperties(prefix = "spring.redis.pool")
        public JedisPoolConfig getRedisConfig(){
            JedisPoolConfig config = new JedisPoolConfig();
            return config;
        }
    
        @Bean
        @ConfigurationProperties(prefix = "spring.redis")
        public JedisConnectionFactory getConnectionFactory() {
            JedisConnectionFactory factory = new JedisConnectionFactory();
            factory.setUsePool(true);
            JedisPoolConfig config = getRedisConfig();
            factory.setPoolConfig(config);
            return factory;
        }
    
        @Bean
        public RedisTemplate<?, ?> getRedisTemplate() {
            JedisConnectionFactory factory = getConnectionFactory();
            factory.setDatabase(2); #设置保存数据的库
            RedisTemplate<?, ?> template = new StringRedisTemplate(factory);
            return template;
        }
    
    }

    4、controller层实现

    @Autowired
        StringRedisTemplate redisTemplate;
    
        @RequestMapping("/showUser")
        @ResponseBody
        public User toIndex(HttpServletRequest request, Model model){
            int userId = Integer.parseInt(request.getParameter("id"));
            User user = this.userService.getUserById(userId);
            redisTemplate.opsForValue().set("user",user.toString());
            return user;
        }

    完毕!

  • 相关阅读:
    定位IO瓶颈的方法,iowait低,IO就没有到瓶颈?
    10分钟检查自己的系统性能数据
    netperf使用指南
    如何看内核源码
    xxx
    os.path 模块
    目前中国智能语音产业的格局、现状
    NLP-python 自然语言处理01
    15本经典金融投资著作
    写给步入工作的自己
  • 原文地址:https://www.cnblogs.com/ywjfx/p/11389134.html
Copyright © 2020-2023  润新知