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

}

  

 

posted @ 2020-09-18 21:40  抽象Java  阅读(150)  评论(0编辑  收藏  举报