使用Java编程和springboot框架统计本周第一天 本月第一天 本年第一天起到今天为止的中奖趋势接口 并对接口进行redis缓存处理 过期时间10分钟给出相应的controller层,service层,service实现类,daoc层及mapper,
时间: 2024-03-10 19:46:54 浏览: 67
好的,以下是对应的代码实现:
**Controller层:**
```java
@RestController
@RequestMapping("/trend")
public class TrendController {
@Autowired
private TrendService trendService;
@GetMapping("/week")
public List<Integer> getWeekTrend() {
return trendService.getWeekTrend();
}
@GetMapping("/month")
public List<Integer> getMonthTrend() {
return trendService.getMonthTrend();
}
@GetMapping("/year")
public List<Integer> getYearTrend() {
return trendService.getYearTrend();
}
}
```
**Service层:**
```java
public interface TrendService {
List<Integer> getWeekTrend();
List<Integer> getMonthTrend();
List<Integer> getYearTrend();
}
```
**Service实现类:**
```java
@Service
public class TrendServiceImpl implements TrendService {
@Autowired
private TrendDao trendDao;
@Autowired
private RedisTemplate<String, List<Integer>> redisTemplate;
@Override
public List<Integer> getWeekTrend() {
String key = "week_trend";
List<Integer> weekTrend = redisTemplate.opsForValue().get(key);
if (weekTrend == null) {
weekTrend = trendDao.getWeekTrend();
redisTemplate.opsForValue().set(key, weekTrend, 10, TimeUnit.MINUTES);
}
return weekTrend;
}
@Override
public List<Integer> getMonthTrend() {
String key = "month_trend";
List<Integer> monthTrend = redisTemplate.opsForValue().get(key);
if (monthTrend == null) {
monthTrend = trendDao.getMonthTrend();
redisTemplate.opsForValue().set(key, monthTrend, 10, TimeUnit.MINUTES);
}
return monthTrend;
}
@Override
public List<Integer> getYearTrend() {
String key = "year_trend";
List<Integer> yearTrend = redisTemplate.opsForValue().get(key);
if (yearTrend == null) {
yearTrend = trendDao.getYearTrend();
redisTemplate.opsForValue().set(key, yearTrend, 10, TimeUnit.MINUTES);
}
return yearTrend;
}
}
```
**Dao层及Mapper:**
```java
@Mapper
@Repository
public interface TrendDao {
List<Integer> getWeekTrend();
List<Integer> getMonthTrend();
List<Integer> getYearTrend();
}
```
```xml
<mapper namespace="com.example.mapper.TrendMapper">
<select id="getWeekTrend" resultType="java.lang.Integer" >
select count(*) from prize where to_days(prize_time) = to_days(now()) - (weekday(now()) + 7) % 7;
</select>
<select id="getMonthTrend" resultType="java.lang.Integer" >
select count(*) from prize where date_format(prize_time, '%Y-%m') = date_format(now(), '%Y-%m');
</select>
<select id="getYearTrend" resultType="java.lang.Integer" >
select count(*) from prize where year(prize_time) = year(now());
</select>
</mapper>
```
以上代码中,我们使用了Redis缓存,当访问量较大时,可以有效地减轻数据库的压力。此外,我们的SQL语句也比较简单,使用了MySQL的日期函数来计算中奖次数。
阅读全文