存储方式

使用Redis做缓存的话,数据的存储结构有两种,一种采用strings存储,另一种是用hashes存储,官方推荐使用hashes

  • strings存储比较简单的,固定的数据,比如存储一个简单的用户信息(用户名、昵称、头像、年龄等)。存储时需要将数据进行序列化,获取时要反序列化。在数据量较小的情况下还是可以忽略这种开销的
  • 但如果存储的的数据可能某些属性会有些变化,比如餐厅数据中,它有likeVotes(喜欢)和dislikeVotes(不喜欢)的数量,这类变的数据,那么我们采用hashes会更好,而且存储的时候没有序列化开销

创建 ms-restaurants模块

编写pom文件和配置文件

读取餐厅信息
RestaurantMapper

// 根据餐厅 ID 查询餐厅信息
@Select("select id, name, cnName, x, y, location, cnLocation, area, telephone, " +
        "email, website, cuisine, average_price, introduction, thumbnail, like_votes," +
        "dislike_votes, city_id, is_valid, create_date, update_date" +
        " from t_restaurants where id = #{id}")
Restaurant findById(@Param("id") Integer id);

RestaurantService
先查询缓存 --> 缓存没有 --> 查询数据库(在更新缓存)

@Service
@Slf4j
public class RestaurantService {

    @Resource
    public RestaurantMapper restaurantMapper;
    @Resource
    public RedisTemplate redisTemplate;

    /**
     * 根据餐厅 ID 查询餐厅数据
     *
     * @param restaurantId
     * @return
     */
    public Restaurant findById(Integer restaurantId) {
        // 请选择餐厅
        AssertUtil.isTrue(restaurantId == null, "请选择餐厅查看");
        // 获取 Key
        String key = RedisKeyConstant.restaurants.getKey() + restaurantId;
        // 获取餐厅缓存
        LinkedHashMap restaurantMap = (LinkedHashMap) redisTemplate.opsForHash().entries(key);
        // 如果缓存不存在,查询数据库
        Restaurant restaurant = null;
        if (restaurantMap == null || restaurantMap.isEmpty()) {
            log.info("缓存失效了,查询数据库:{}", restaurantId);
            // 查询数据库
            restaurant = restaurantMapper.findById(restaurantId);
            if (restaurant != null) {
                // 更新缓存
                redisTemplate.opsForHash().putAll(key, BeanUtil.beanToMap(restaurant));
            }
        } else {
            restaurant = BeanUtil.fillBeanWithMap(restaurantMap,
                    new Restaurant(), false);
        }
        return restaurant;
    }

}

RestaurantController省略,启动类、网关配置省略


缓存淘汰

最大内存参数
redis数据库的最大缓存、主键失效、淘汰机制等参数都是通过配置文件来配置的。这个文件是我们的redis.config文件。
maxmemory <bytes>:设置最大内存
image.png


Natcret
1 声望0 粉丝