zoukankan      html  css  js  c++  java
  • redis整合spring (二)

    config

    @Configuration //
    public class AppConfig {
    
        @Value("${spring.redis.host}")
        String host;
    
        @Value("${spring.redis.port}")
        int port;
    
    
        // 创建对象,spring托管 <bean ...
        @Bean
        public JedisPool jedisPool() {
            JedisPool jedisPool = new JedisPool("localhost", 6379);
            return jedisPool;
        }
    
        @Bean
        public RedisTemplate redisTemplate(){
            RedisTemplate redisTemplate = new RedisTemplate();
            redisTemplate.setConnectionFactory(redisConnectionFactory());
            return redisTemplate;
        }
    
        public RedisConnectionFactory redisConnectionFactory(){
            RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
            redisStandaloneConfiguration.setHostName(host);
            redisStandaloneConfiguration.setPort(port);
            RedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory(redisStandaloneConfiguration);
            return redisConnectionFactory;
        }
    
    }
    

    service

    @Service
    public class UserService {
    
        @Autowired
        JdbcTemplate jdbcTemplate; // spring提供jdbc一个工具(mybastis类似)
    
        @Autowired
        RedisTemplate redisTemplate;
    
        /**
         * 根据ID查询用户信息 (redis缓存,用户信息以json字符串格式存在(序列化))
         */
        public User findUserById(String userId) {
            // 1、read cache
            User user = null;
            Object result = (User)redisTemplate.opsForValue().get("userId");
            if(user != null){
                return (User)result;
            }
    
            // 2、查询数据库
            String sql = "select * from tb_user_base where uid=?";
            user = jdbcTemplate.queryForObject(sql, new String[]{userId}, new BeanPropertyRowMapper<>(User.class));
    
            // set cache
            redisTemplate.opsForValue().set(userId, user);
            return user;
        }
    
    }
    

      

  • 相关阅读:
    BZOJ3413: 匹配
    BZOJ5084: hashit
    BZOJ2281: [Sdoi2011]黑白棋
    BZOJ4808: 马
    BZOJ3208: 花神的秒题计划Ⅰ
    BZOJ3714: [PA2014]Kuglarz
    BZOJ2102: [Usaco2010 Dec]The Trough Game
    JZOJ6676. 【2020.06.01省选模拟】查拉图斯特拉如是说 (第二类斯特林数+多项式多点求值)
    LOJ #3217. 「PA 2019」Desant(状压dp)
    JZOJ 5154.【NOI2017模拟6.20】树形图求和 (矩阵树定理)
  • 原文地址:https://www.cnblogs.com/Jomini/p/13693648.html
Copyright © 2011-2022 走看看