Redis构建频次访问控制器(一)

Redis频次访问控制器

设计思路
频次控制旨在控制某个用户接触到某个广告的次数,以达到提高广告性价比的目的,一般来说,随着某个用户看到同一个广告频次的逐渐上升,点击率呈逐渐下降的趋势,因此在按照CPM采买流量时,广告主有时会要求根据品次控制某个用户接触到某次广告的次数

  • 首先,使用redis的hash类型来构建用户,广告,频次访问限制
  • 其次,使用用户+广告id为key,来构建用户对某广告的访问频次统计
# HMSET userID adID reqFrequency,使用HMSET构建用户,广告和访问频次的关系
127.0.0.1:6379> HMSET 12345 1 3
OK
# 初始化广告的访问频次
127.0.0.1:6379> set 12345_1 0
OK
#设置过期时间
127.0.0.1:6379> EXPIREAT 12345_1 1513239705
(integer) 1
#增加广告访问频次
127.0.0.1:6379> INCR 12345_1
(integer) 1
#获取用户访问的某个广告的频次
127.0.0.1:6379> HMGET 12345 1
1) "3"

Java源码

明天使用springclou分布式和schedule定时任务
可以的话在加上caffeine二级缓存
整体结构
在这里插入图片描述

数据库代码

### 模拟redis频次过滤数据库
CREATE TABLE ad_user(
	uid INT(10) PRIMARY KEY NOT NULL,
	aid INT(10) NOT NULL
)
INSERT INTO ad_user VALUES(1000,2000);
INSERT INTO ad_user VALUES(1001,2001);
INSERT INTO ad_user VALUES(1002,2002);

每个部分的代码
启动类

package com.xfgg.demo;

import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@MapperScan("com.xfgg.demo.dao")
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

配置文件

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    database: 0
  datasource:
    url: jdbc:mysql://localhost:3306/ad_user_time
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: 123456
server:
  port: 8900

config

package com.xfgg.demo.config;

import org.springframework.beans.factory.annotation.Value;
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 org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Map;

@Configuration
public class RedisConfig {

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.database}")
    private int databaseId;

    @Bean
    @ConfigurationProperties(prefix = "spring.redis")
    public JedisPoolConfig getRedisConfig() {
        JedisPoolConfig config = new JedisPoolConfig();
        return config;
    }

    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setUsePool(true);
        JedisPoolConfig config = getRedisConfig();
        factory.setPoolConfig(config);
        factory.setHostName(host);
        factory.setPort(port);
        factory.setDatabase(databaseId);
        return factory;
    }
    @Bean
    public RedisTemplate<?, ?> getRedisTemplate(){
        return new StringRedisTemplate(jedisConnectionFactory());
    }

    @Bean("user_test")
    public RedisTemplate<String, Map<String, String>> redisTemplate() {
        final RedisTemplate<String, Map<String, String>> template = new RedisTemplate<>();
        template.setConnectionFactory(jedisConnectionFactory());

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        template.setHashValueSerializer(stringRedisSerializer);
        return template;
    }
}

constant

package com.xfgg.demo.constant;

public interface AdShowTimes {
    String AD_LIMIT_TIMES="10";
}

controller
AdshowController

package com.xfgg.demo.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AdShowController {
    @RequestMapping("/show/{uid}/{aid}")
    public String show(@PathVariable("uid") String uid,
                       @PathVariable("aid") String aid){
        return "调用了广告服务接口,频次加1";
    }
}

AdUserController

package com.xfgg.demo.controller;


import com.xfgg.demo.entity.AdUser;
import com.xfgg.demo.service.AdUserService;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class AdUserController {
    @Resource
    private AdUserService adUserService;
    @RequestMapping("")
    public List<AdUser> findAll(){
        return adUserService.findAll();
    }
}

RedisFilterController

package com.xfgg.demo.controller;

import com.xfgg.demo.service.RedisFilterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RedisFilterController {
    @Autowired
    private RedisFilterService filterService;
    @RequestMapping("/redis")
    public void setData(){
        filterService.setData();
    }
    @RequestMapping("/re")
    public void setData2(){
        filterService.setData2();
    }
}

dao

package com.xfgg.demo.dao;

import com.xfgg.demo.entity.AdUser;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;

@Mapper
public interface AdUserDao{
    @Select("select * from ad_user")
    List<AdUser> findAll();
}

entiry

package com.xfgg.demo.entity;

import lombok.Data;

@Data
public class AdUser {
    private String uid;
    private String aid;
}

service
AdUserService

package com.xfgg.demo.service;

import com.xfgg.demo.entity.AdUser;

import java.util.List;

public interface AdUserService {
    List<AdUser> findAll();
}

RedisFilterService

package com.xfgg.demo.service;

public interface RedisFilterService {
    将数据库数据加入到redis缓存中
    void setData();
    uid_aid为key,times为value,放入redis缓存中
    void setData2();
    //根据传入的广告id和用户id增加指定用户的频次
}

impl
AdUserServiceImpl

package com.xfgg.demo.service.impl;

import com.xfgg.demo.dao.AdUserDao;
import com.xfgg.demo.entity.AdUser;
import com.xfgg.demo.service.AdUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AdUserServiceImpl implements AdUserService{
    @Resource
    private AdUserDao adUserDao;

    @Override
    public List<AdUser> findAll() {
        return adUserDao.findAll();
    }
}

RedisFilterServiceImpl

package com.xfgg.demo.service.impl;

import com.xfgg.demo.constant.AdShowTimes;
import com.xfgg.demo.service.AdUserService;
import com.xfgg.demo.service.RedisFilterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class RedisFilterServiceImpl implements RedisFilterService {
    @Autowired
    private AdUserService adUserService;
    @Resource(name = "user_test")
    private RedisTemplate<String, Map<String,String>> redisTemplate;
    @Resource
    private RedisTemplate<String,String> redisTemplate1;
    //将数据库数据加入到redis缓存中
    @Override
    public void setData(){
        for (int i =0;i<adUserService.findAll().size();i++){
            Map<String,String> results = new HashMap<>();
            results.put(adUserService.findAll().get(i).getUid(),"0");
            redisTemplate.opsForHash().putAll(adUserService.findAll().get(i).getAid(),results);
            //设置过期时间
            redisTemplate.expire(adUserService.findAll().get(i).getAid(),60*10,TimeUnit.SECONDS);
        }
    }
    //uid_aid为key,times为value,放入redis缓存中
    //后续改为caffeine缓存,重置操作也加入定时任务中,每天清零
    @Override
    public void setData2(){
        for (int i=0;i<adUserService.findAll().size();i++){
            redisTemplate1.opsForValue().set(adUserService.findAll().get(i).getUid()+"_"+adUserService.findAll().get(i).getAid()
                    , AdShowTimes.AD_LIMIT_TIMES);
        }
    }

}

效果图
在这里插入图片描述

具体页面效果还没做

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值