1.SpringMVC在项目中的应用?
1)service层,项目的业务逻辑层,一般先定义一个接口,在写一个实现类,实现所有的接口方法。service的实现类中要加注解@Service(用于标注业务层组件),@Resource 注入dao组件,方便在业务层中调用对用dao的方法.
@Service
public class ContentServiceImpl implements ContentService{
@Autowired
private ContentDao contentdao;
2)controller层,控制层它把用户请求的数据经过业务处理层处理之后封装成一个Model ,然后再把该Model 返回给对应的View 进行展示。controller要添加注解@Controller(用于标注控制层组件)),@Resource 注入service组件,方便调用业务层的方法.
@Controller
public class ContentController {
@Autowired
private ContentService contentService;
//用户评论 提交 按钮--insert
@RequestMapping("/ContentController")
@ResponseBody
public Object addByText( @ModelAttribute("content") Content content,HttpServletRequest request){
content.setUsername(((User)(request.getSession().getAttribute("sessionuser"))).getUsername());
contentService.addByText(content);
return new Gson().toJson(contentService.queryOneForJustNow());
}
2.Redis缓存数据存放的时间?
列:在实现积分项目业务中,对不同场景设置了不同的key-value缓存到了redis中。但是因为对不同业务的key需要缓存的时间不尽相同,这里自定义工具类来实现。
设置redis缓存key,截取部分代码:
try{ //cacheManager就相当从redis链接池获取一个连接,具体工厂类获取在后面备注 cacheManager = (RedisCacheManager) CacheManagerFactory.getCacheManager(); totalMonCount = Float.parseFloat(cacheManager.getString(monthKey)) + centCount; if (centLimitByMonth != -1){ if (totalMonCount > centLimitByMonth) { // 超出月上限不再累计 logger.error("exceeds the month limit cents! [" + totalMonCount + "] code:[" + code + "]"); return null; } } //当未超出月额度,此时要对日额度进行判断;只需判断其是否超出日上限积分 if (dayKey != null){ //累积积分;因为签到其实是没有每日积分的,是按次数规则累积的;但为了统一,直接用centCount代替(都是签一次1分) totalDayCount = Float.parseFloat(cacheManager.getString(dayKey)) + centCount; if (centLimitByDay != -1){ if (totalDayCount > centLimitByDay){ logger.info("[ERROR]teacher everyday assign cents > month limit! total: ["+totalDayCount+"]"); return null; } } cacheManager.set(dayKey,totalDayCount.toString(),DateUtil.getSecsToEndOfCurrentDay()); } //对月限制key进行积分累加 //每月1号凌晨1点启动脚本删除,同时设置了保存到月底缓存时间双重保障 cacheManager.set(monthKey, totalMonCount.toString(), DateUtil.getSecsToEndOfCurrentDay()); logger.info("==monthkey:"+monthKey+"---value:"+totalMonCount); } ... }catch(Exception e){ logger.error("===cache redis fail!"); e.printStackTrace(); }finally { if (cacheManager != null){ cacheManager.close(); } } //工厂类获取redis链接 public class CacheManagerFactory { private static ICacheManager cacheManager; private CacheManagerFactory(){ }; public static ICacheManager getCacheManager(){ if(cacheManager == null){ synchronized (CacheManagerFactory.class) { if(cacheManager == null){ JedisPooler jedisPooler = RedisPoolerFactory.getJedisPooler(); cacheManager = new RedisCacheManager(jedisPooler); } } } return cacheManager; } } //redis链接池工厂类获取链接 public class RedisPoolerFactory { private static JedisPooler jedisPooler; private RedisPoolerFactory(){ }; public static JedisPooler getJedisPooler(){ if(jedisPooler == null){ synchronized (RedisPoolerFactory.class) { if(jedisPooler == null){ jedisPooler = new JedisPooler(); } } } return jedisPooler; } } /** * * Redis 连接池实例 * * @author Ethan.Lam * @createTime 2011-12-3 * */ public class JedisPooler { private JedisPool pool; private String REDIS_HOST; private String REDIS_PSW; private int REDIS_PORT; private int REDIS_MaxActive; private int REDIS_MaxIdle; private int REDIS_MaxWait; public JedisPooler(String config) { __init(config); } public JedisPooler() { __init("/jedisPool.properties"); } private void __init(String conf) { // 完成初始化工作 Properties prop = new Properties(); try { InputStream _file = loadConfig(conf); prop.load(_file); REDIS_HOST = prop.getProperty("REDIS.HOST"); REDIS_PSW = prop.getProperty("REDIS.PSW"); REDIS_PORT = Integer.parseInt(prop.getProperty("REDIS.PORT").trim()); REDIS_MaxActive = Integer.parseInt(prop.getProperty("REDIS.MaxActive").trim()); REDIS_MaxIdle = Integer.parseInt(prop.getProperty("REDIS.MaxIdle").trim()); REDIS_MaxWait = Integer.parseInt(prop.getProperty("REDIS.MaxWait").trim()); } catch (Exception e) { e.printStackTrace(); REDIS_HOST = "localhost"; throw new NullPointerException(conf + " is not found !"); } JedisPoolConfig config = new JedisPoolConfig(); config.setMaxActive(REDIS_MaxActive); config.setMaxIdle(REDIS_MaxIdle); config.setMaxWait(REDIS_MaxWait); config.setTestOnBorrow(true); System.out.println("REDIS Cache服务信息: 当前连接的服务IP为:" + REDIS_HOST + ":" + REDIS_PORT); if (null == REDIS_PSW || "".equals(REDIS_PSW.trim())){ pool = new JedisPool(config, REDIS_HOST, REDIS_PORT, 5000); } else{ pool = new JedisPool(config, REDIS_HOST, REDIS_PORT, 5000, REDIS_PSW); } } public Jedis getJedis() { return pool.getResource(); } public void returnResource(Jedis jedis) { pool.returnResource(jedis); } public JedisPool getPool() { return pool; } InputStream loadConfig(String configPath) throws Exception { InputStream _file = null; try { String file = JedisPooler.class.getResource(configPath).getFile(); file = URLDecoder.decode(file); _file = new FileInputStream(file); } catch (Exception e) { System.out.println("读取jar中的配置文件...."); String currentJarPath = URLDecoder.decode(JedisPooler.class.getProtectionDomain() .getCodeSource().getLocation().getFile(), "UTF-8"); // 获取当前Jar文件名 System.out.println("currentJarPath:" + currentJarPath); java.util.jar.JarFile currentJar = new java.util.jar.JarFile(currentJarPath); java.util.jar.JarEntry dbEntry = currentJar.getJarEntry("jedisPool.properties"); InputStream in = currentJar.getInputStream(dbEntry); _file = in; } return _file; } }