首页 > 编程语言 > 详细

Redis整合Spring(二)

时间:2020-09-18 23:07:18      阅读:46      评论:0      收藏:0      [点我收藏+]

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;
    }

}

  

 

Redis整合Spring(二)

原文:https://www.cnblogs.com/Jomini/p/13693648.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!