提交 fec4d66e 编写于 作者: 梦境迷离's avatar 梦境迷离

使用宏注解替代日志使用,处理404错误,优化代码

上级 fadf6b5e
......@@ -11,8 +11,8 @@ mybatis.configuration.default-statement-timeout=30
# Datasource
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/websocket?useUnicode=true&useSSL=false&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=xx
spring.datasource.username=用自己的
spring.datasource.password=用自己的
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.platform=mysql
#jdbc自动初始化数据库
......@@ -26,8 +26,8 @@ server.port=80
server.session.timeout=1800
# Email
spring.mail.host=smtp.qq.com
spring.mail.username=568845948@qq.com
spring.mail.password=
spring.mail.username=用自己的
spring.mail.password=用自己的
spring.mail.port=587
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
......
package io.github.dreamylost.config
import com.fasterxml.jackson.annotation.JsonAutoDetect
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.PropertyAccessor
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.ScalaObjectMapper
import io.github.dreamylost.log
import io.github.dreamylost.logs.LogType
import org.springframework.beans.factory.annotation.Value
import org.springframework.cache.CacheManager
import org.springframework.cache.annotation.CachingConfigurerSupport
......@@ -17,14 +24,6 @@ import org.springframework.data.redis.core.RedisTemplate
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer
import org.springframework.data.redis.serializer.StringRedisSerializer
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.ScalaObjectMapper
import java.lang.reflect.Method
......@@ -35,10 +34,9 @@ import java.lang.reflect.Method
*/
@EnableCaching
@Configuration
@log(logType = LogType.Slf4j)
class CacheConfig extends CachingConfigurerSupport {
private final lazy val LOGGER: Logger = LoggerFactory.getLogger(classOf[CacheConfig])
//允许超时
@Value("${spring.redis.timeout}")
private var timeout: Int = _
......@@ -48,7 +46,7 @@ class CacheConfig extends CachingConfigurerSupport {
val cacheManager = new RedisCacheManager(redisTemplate)
//设置key-value过期时间
cacheManager.setDefaultExpiration(timeout)
LOGGER.info("Init the CacheManager Finished")
log.info("Init the CacheManager Finished")
cacheManager
}
......
package io.github.dreamylost.config
import io.github.dreamylost.log
import io.github.dreamylost.logs.LogType
import org.springframework.boot.autoconfigure.web.ErrorController
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.RequestMapping
/** 错误处理器
*
* @author 梦境迷离
* @since 2021/11/28
* @version 1.0
*/
@Controller
@log(logType = LogType.Slf4j)
class CustomErrorController extends ErrorController {
private final val ERROR_PATH = "/error"
@RequestMapping(value = Array(ERROR_PATH))
def handleError: String = "404"
def getErrorPath: String = ERROR_PATH
}
package io.github.dreamylost.config
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.servlet.ModelAndView
import javax.servlet.http.HttpServletRequest
/** 异常处理器
*
* @author 梦境迷离
* @since 2021/11/22
* @version 1.0
*/
@ControllerAdvice
class GlobalExceptionAdvice {
private final lazy val LOGGER: Logger = LoggerFactory.getLogger(classOf[GlobalExceptionAdvice])
@ExceptionHandler(Array(classOf[Exception]))
def customException(request: HttpServletRequest, e: Exception): ModelAndView = {
LOGGER.error("自定义异常处理:", e)
val mv = new ModelAndView
mv.addObject("message", e.getMessage)
mv.setViewName("500")
mv
}
}
package io.github.dreamylost.config
import com.github.pagehelper.PageHelper
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import io.github.dreamylost.log
import io.github.dreamylost.logs.LogType
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
......@@ -14,13 +14,12 @@ import java.util.Properties
* @author 梦境迷离
*/
@Configuration
@log(logType = LogType.Slf4j)
class MybatisConfig {
private final lazy val LOGGER: Logger = LoggerFactory.getLogger(classOf[MybatisConfig])
@Bean
def pageHelper(): PageHelper = {
LOGGER.info("注册MyBatis分页插件PageHelper")
log.info("注册MyBatis分页插件PageHelper")
val pageHelper = new PageHelper()
val properties = new Properties()
properties.setProperty(
......
package io.github.dreamylost.config
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import io.github.dreamylost.log
import io.github.dreamylost.logs.LogType
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
......@@ -14,9 +14,9 @@ import redis.clients.jedis.JedisPoolConfig
* @author 梦境迷离
*/
@Configuration
@log(logType = LogType.Slf4j)
class RedisConfig {
private final lazy val LOGGER: Logger = LoggerFactory.getLogger(classOf[RedisConfig])
//主机地址
@Value("${spring.redis.host}")
private var host: String = _
......@@ -55,7 +55,7 @@ class RedisConfig {
jedisPoolConfig.setMaxIdle(maxIdle)
jedisPoolConfig.setMinIdle(minIdle)
jedisPoolConfig.setMaxWaitMillis(maxWait)
LOGGER.info("Init the RedisPoolConfig Finished")
log.info("Init the RedisPoolConfig Finished")
jedisPoolConfig
}
......@@ -72,7 +72,7 @@ class RedisConfig {
factory.setPassword(password)
factory.setDatabase(database)
factory.setPoolConfig(poolConfig)
LOGGER.info("Init the Redis instance Finished")
log.info("Init the Redis instance Finished")
factory
}
......
package io.github.dreamylost.config
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.ScalaObjectMapper
import io.github.dreamylost.util.Jackson
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
......@@ -14,7 +10,6 @@ import org.springframework.web.servlet.config.annotation.InterceptorRegistry
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
import io.github.dreamylost.util.Jackson
/** SpringMVC配置
*
......
package io.github.dreamylost.config
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import io.github.dreamylost.log
import io.github.dreamylost.logs.LogType
import org.springframework.web.servlet.HandlerInterceptor
import org.springframework.web.servlet.ModelAndView
......@@ -13,10 +13,9 @@ import javax.servlet.http.HttpServletResponse
* @since 2018年9月8日
* @author 梦境迷离
*/
@log(logType = LogType.Slf4j)
class SystemHandlerInterceptor extends HandlerInterceptor {
private final lazy val LOGGER: Logger = LoggerFactory.getLogger(classOf[SystemHandlerInterceptor])
/** 前置处理器,在请求处理之前调用
*
* @param request
......@@ -29,7 +28,7 @@ class SystemHandlerInterceptor extends HandlerInterceptor {
response: HttpServletResponse,
handler: Object
): Boolean = {
LOGGER.debug("前置处理器,在请求处理之前调用")
log.debug("前置处理器,在请求处理之前调用")
if (request.getSession.getAttribute("user") == null) {
response.sendRedirect("/")
false
......@@ -49,7 +48,7 @@ class SystemHandlerInterceptor extends HandlerInterceptor {
handler: Object,
modelAndView: ModelAndView
): Unit = {
LOGGER.debug("请求处理之后,视图渲染之前调用")
log.debug("请求处理之后,视图渲染之前调用")
}
/** 后置处理器,渲染视图完成
......@@ -65,6 +64,6 @@ class SystemHandlerInterceptor extends HandlerInterceptor {
handler: Object,
ex: Exception
): Unit = {
LOGGER.debug("后置处理器,在请求处理之后调用")
log.debug("后置处理器,在请求处理之后调用")
}
}
......@@ -66,4 +66,14 @@ object SystemConstant {
final val ADD_MESSAGE_PAGE = 4
final val GROUP_TYPE = "group"
final val FRIEND_TYPE = "friend"
object status {
val ONLINE = "online"
val ONLINE_DESC = "在线"
val HIDE_DESC = "离线"
}
}
package io.github.dreamylost.controller
import com.github.pagehelper.PageHelper
import io.github.dreamylost.ResultPageSet
import io.github.dreamylost.ResultSet
import io.github.dreamylost.constant.SystemConstant
import io.github.dreamylost.logs.LogType
import io.github.dreamylost.model._
import io.github.dreamylost.model.domains.UserVo
import io.github.dreamylost.model.domains._
import io.github.dreamylost.model.entities.FriendGroup
......@@ -13,21 +13,21 @@ import io.github.dreamylost.service.CookieService
import io.github.dreamylost.service.UserService
import io.github.dreamylost.util.FileUtil
import io.github.dreamylost.util.SecurityUtil
import io.github.dreamylost.ResultPageSet
import io.github.dreamylost.ResultSet
import io.github.dreamylost.log
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation._
import org.springframework.web.multipart.MultipartFile
import io.github.dreamylost.model._
import java.util
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import scala.collection.JavaConverters._
import scala.jdk.CollectionConverters._
/** 用户接口
*
......@@ -37,10 +37,9 @@ import scala.collection.JavaConverters._
@Controller
@Api(value = "用户相关操作")
@RequestMapping(value = Array("/user"))
@log(logType = LogType.Slf4j)
class UserController @Autowired() (userService: UserService, cookieService: CookieService) {
private final lazy val LOGGER: Logger = LoggerFactory.getLogger(classOf[UserController])
/** 退出群
*
* @param groupId 群编号
......@@ -166,7 +165,7 @@ class UserController @Autowired() (userService: UserService, cookieService: Cook
@RequestParam(value = "sex", required = false) sex: Integer
): ResultPageSet = {
val count = userService.countUsers(name, sex)
LOGGER.info(s"find users => [total = $count]")
log.info(s"find users => [total = $count]")
val pages =
if (count < SystemConstant.USER_PAGE) 1
else {
......@@ -284,7 +283,7 @@ class UserController @Autowired() (userService: UserService, cookieService: Cook
@PostMapping(Array("/getOffLineMessage"))
def getOffLineMessage(request: HttpServletRequest): ResultSet = {
val user = request.getSession.getAttribute("user").asInstanceOf[User]
LOGGER.info(s"find offline msg [uid = ${user.id}]")
log.info(s"find offline msg [uid = ${user.id}]")
val groups = userService.findGroupsById(user.id).asScala.map(_.id).toList
val groupMsg = groups.flatMap(gId => userService.findOffLineMessage(gId, 0).asScala)
val useMsg = userService.findOffLineMessage(user.id, 0).asScala.toList
......@@ -351,7 +350,7 @@ class UserController @Autowired() (userService: UserService, cookieService: Cook
if (u != null && "nonactivated".equals(u.status)) {
ResultSet(code = SystemConstant.ERROR, msg = SystemConstant.NONACTIVED)
} else if (u != null && !"nonactivated".equals(u.status)) {
LOGGER.info(s"user login success => [user = $user, u = $u]")
log.info(s"user login success => [user = $user, u = $u]")
request.getSession.setAttribute("user", u)
cookieService.addCookie(user, request, response)
ResultSet(u)
......@@ -373,7 +372,7 @@ class UserController @Autowired() (userService: UserService, cookieService: Cook
//用户信息
val user = userService.findUserById(userId)
val data = FriendAndGroupInfo(
mine = user.copy(status = "online"), // 怎么区分主动刷新?这样如果主动刷新会将隐式重置为在线
mine = user.copy(status = SystemConstant.status.ONLINE), // 怎么区分主动刷新?这样如果主动刷新会将隐式重置为在线
friend = userService.findFriendGroupsById(userId).asScala.toList,
group = userService.findGroupsById(userId).asScala.toList
)
......@@ -413,7 +412,7 @@ class UserController @Autowired() (userService: UserService, cookieService: Cook
val result = new util.HashMap[String, String]
//图片的相对路径地址
result.put("src", src)
LOGGER.info("图片" + file.getOriginalFilename + "上传成功")
log.info("图片" + file.getOriginalFilename + "上传成功")
ResultSet(result)
}
}
......@@ -438,7 +437,7 @@ class UserController @Autowired() (userService: UserService, cookieService: Cook
val result = new util.HashMap[String, String]
//图片的相对路径地址
result.put("src", src)
LOGGER.info("图片" + file.getOriginalFilename + "上传成功")
log.info("图片" + file.getOriginalFilename + "上传成功")
ResultSet(result)
}
}
......@@ -499,7 +498,7 @@ class UserController @Autowired() (userService: UserService, cookieService: Cook
//文件的相对路径地址
result.put("src", src)
result.put("name", file.getOriginalFilename)
LOGGER.info("文件" + file.getOriginalFilename + "上传成功")
log.info("文件" + file.getOriginalFilename + "上传成功")
ResultSet(result)
}
}
......@@ -570,7 +569,7 @@ class UserController @Autowired() (userService: UserService, cookieService: Cook
def index(model: Model, request: HttpServletRequest): String = {
val user = request.getSession.getAttribute("user")
model.addAttribute("user", user)
LOGGER.info(s"user access server => [user = $user]")
log.info(s"user access server => [user = $user]")
"index"
}
......
package io.github.dreamylost.service
import io.github.dreamylost.log
import io.github.dreamylost.logs.LogType
import io.github.dreamylost.model.entities.User
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import java.util.Base64
......@@ -16,10 +16,9 @@ import javax.servlet.http.HttpServletResponse
* @since 2018-10-19
*/
@Service
@log(logType = LogType.Slf4j)
class CookieService {
private final lazy val LOGGER: Logger = LoggerFactory.getLogger(classOf[CookieService])
def addCookie(user: User, request: HttpServletRequest, response: HttpServletResponse) {
val baseE: Base64.Encoder = Base64.getEncoder
val baseD: Base64.Decoder = Base64.getDecoder
......@@ -28,7 +27,7 @@ class CookieService {
if ("true" == loginkeeping) {
//使用token,通过Redis
//val uID = UUIDUtil.getUUID32String()
LOGGER.info(s"add cookie for user => [email = ${user.email}]")
log.info(s"add cookie for user => [email = ${user.email}]")
//简单处理,cookie key不能使用=号
val userCookie = new Cookie(
new String(baseE.encode(user.email.getBytes)).replace("=", ""),
......@@ -44,7 +43,7 @@ class CookieService {
for (cookie <- cookies) {
val cookieName = new String(baseD.decode(cookie.getName))
if (cookieName == user.email) {
LOGGER.info(
log.info(
s"remove cookie for user => [email = ${user.email}, cookie name = $cookieName]"
)
cookie.setMaxAge(0)
......@@ -54,7 +53,7 @@ class CookieService {
}
} catch {
case e: Exception =>
LOGGER.error(s"failed in cookie service: $e")
log.error(s"failed in cookie service: $e")
}
}
}
......
package io.github.dreamylost.service
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import io.github.dreamylost.log
import io.github.dreamylost.logs.LogType
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.core.io.FileSystemResource
......@@ -19,10 +19,9 @@ import javax.mail.MessagingException
* @author 梦境迷离
*/
@Service
@log(logType = LogType.Slf4j)
class MailService @Autowired() (sender: JavaMailSender) {
private final lazy val LOGGER: Logger = LoggerFactory.getLogger(classOf[MailService])
@Value("${spring.mail.username}")
private var username: String = _
......@@ -40,10 +39,10 @@ class MailService @Autowired() (sender: JavaMailSender) {
message.setText(content)
try {
sender.send(message)
LOGGER.info("发送给 " + to + " 邮件发送成功")
log.info("发送给 " + to + " 邮件发送成功")
} catch {
case ex: Exception => {
LOGGER.info("发送给 " + to + " 邮件发送失败!" + ex.getMessage)
log.info("发送给 " + to + " 邮件发送失败!" + ex.getMessage)
}
}
}
......@@ -63,10 +62,10 @@ class MailService @Autowired() (sender: JavaMailSender) {
helper.setText(content, true)
try {
sender.send(message)
LOGGER.info("发送给 " + to + " html格式的邮件发送成功")
log.info("发送给 " + to + " html格式的邮件发送成功")
} catch {
case ex: MessagingException => {
LOGGER.info("发送给 " + to + " html格式的邮件发送失败!" + ex.getMessage)
log.info("发送给 " + to + " html格式的邮件发送失败!" + ex.getMessage)
}
}
}
......@@ -90,10 +89,10 @@ class MailService @Autowired() (sender: JavaMailSender) {
helper.addAttachment(fileName, file)
try {
sender.send(message)
LOGGER.info("发送给 " + to + " 带附件邮件发送成功")
log.info("发送给 " + to + " 带附件邮件发送成功")
} catch {
case ex: MessagingException => {
LOGGER.info("发送给 " + to + " 带附件邮件发送失败!" + ex.getMessage)
log.info("发送给 " + to + " 带附件邮件发送失败!" + ex.getMessage)
}
}
}
......@@ -123,10 +122,10 @@ class MailService @Autowired() (sender: JavaMailSender) {
helper.addInline(rscId, res)
try {
sender.send(message)
LOGGER.info("发送给 " + to + " 嵌入静态资源的邮件发送成功")
log.info("发送给 " + to + " 嵌入静态资源的邮件发送成功")
} catch {
case ex: MessagingException => {
LOGGER.info("发送给 " + to + " 嵌入静态资源的邮件发送失败!" + ex.getMessage)
log.info("发送给 " + to + " 嵌入静态资源的邮件发送失败!" + ex.getMessage)
}
}
}
......
package io.github.dreamylost.service
import io.github.dreamylost.constant.SystemConstant
import io.github.dreamylost.log
import io.github.dreamylost.logs.LogType
import io.github.dreamylost.model.domains._
import io.github.dreamylost.model.entities._
import io.github.dreamylost.repository.UserRepository
......@@ -8,17 +10,15 @@ import io.github.dreamylost.util.DateUtil
import io.github.dreamylost.util.SecurityUtil
import io.github.dreamylost.util.UUIDUtil
import io.github.dreamylost.util.WebUtil
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.cache.annotation.CacheEvict
import org.springframework.cache.annotation.Cacheable
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.logging.{ Logger => _ }
import java.util
import javax.servlet.http.HttpServletRequest
import scala.collection.JavaConverters._
import scala.jdk.CollectionConverters._
/** 用户信息相关操作
*
......@@ -26,10 +26,9 @@ import scala.collection.JavaConverters._
* @author 梦境迷离
*/
@Service
@log(logType = LogType.Slf4j)
class UserService @Autowired() (userRepository: UserRepository, mailService: MailService) {
private final val LOGGER: Logger = LoggerFactory.getLogger(classOf[UserService])
/** 退出群
*
* @param gid 群组id
......@@ -177,10 +176,9 @@ class UserService @Autowired() (userRepository: UserRepository, mailService: Mai
if (userRepository.addFriend(add) != 0) updateAddMessage(messageBoxId, 1)
else false
} catch {
case ex: Exception => {
LOGGER.error("重复添好友", ex)
case ex: Exception =>
log.error("重复添好友", ex)
false
}
}
}
......@@ -238,7 +236,7 @@ class UserService @Autowired() (userRepository: UserRepository, mailService: Mai
info.copy(content = "申请加入 '" + group.groupname + "' 群聊中!")
} else info
}
LOGGER.info(infoCopy.toString)
log.info(infoCopy.toString)
ret.add(infoCopy.copy(href = null, user = findUserById(infoCopy.from)))
}
ret
......@@ -257,7 +255,7 @@ class UserService @Autowired() (userRepository: UserRepository, mailService: Mai
@Transactional
def readFriendMessage(mine: Int, to: Int): Boolean = {
userRepository.readMessage(mine, to, "friend") == 1
userRepository.readMessage(mine, to, SystemConstant.FRIEND_TYPE) == 1
}
/** 将本群中的所有消息对我标记为已读
......@@ -267,7 +265,7 @@ class UserService @Autowired() (userRepository: UserRepository, mailService: Mai
*/
@Transactional
def readGroupMessage(gId: Int, to: Int): Boolean = {
userRepository.readMessage(gId, to, "group") == 1
userRepository.readMessage(gId, to, SystemConstant.GROUP_TYPE) == 1
}
/** 添加好友、群组信息请求
......@@ -321,8 +319,8 @@ class UserService @Autowired() (userRepository: UserRepository, mailService: Mai
*/
def countHistoryMessage(uid: Int, mid: Int, `type`: String): Int = {
`type` match {
case "friend" => userRepository.countHistoryMessage(uid, mid, `type`)
case "group" => userRepository.countHistoryMessage(null, mid, `type`)
case SystemConstant.FRIEND_TYPE => userRepository.countHistoryMessage(uid, mid, `type`)
case SystemConstant.GROUP_TYPE => userRepository.countHistoryMessage(null, mid, `type`)
}
}
......@@ -336,7 +334,7 @@ class UserService @Autowired() (userRepository: UserRepository, mailService: Mai
*/
def findHistoryMessage(user: User, mid: Int, `type`: String): util.List[ChatHistory] = {
//单人聊天记录
val list = if ("friend".equals(`type`)) {
val list = if (SystemConstant.FRIEND_TYPE.equals(`type`)) {
//查找聊天记录
val historys: util.List[Receive] = userRepository.findHistoryMessage(user.id, mid, `type`)
val toUser = findUserById(mid)
......@@ -353,7 +351,7 @@ class UserService @Autowired() (userRepository: UserRepository, mailService: Mai
ChatHistory(history.id, user.username, user.avatar, history.content, history.timestamp)
}
}
} else if ("group".equals(`type`)) {
} else if (SystemConstant.GROUP_TYPE.equals(`type`)) {
//群聊天记录
//查找聊天记录
val historys = userRepository.findHistoryMessage(null, mid, `type`)
......@@ -507,7 +505,7 @@ class UserService @Autowired() (userRepository: UserRepository, mailService: Mai
password = SecurityUtil.encrypt(user.password)
)
userRepository.saveUser(userCopy)
LOGGER.info("userid = " + userCopy.id)
log.info("userid = " + userCopy.id)
//创建默认的好友分组
createFriendGroup(SystemConstant.DEFAULT_GROUP_NAME, userCopy.id)
//发送激活电子邮件
......
package io.github.dreamylost.websocket
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import io.github.dreamylost.log
import io.github.dreamylost.logs.LogType
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.stereotype.Service
......@@ -15,10 +15,9 @@ import java.util.concurrent.TimeUnit
* @author 梦境迷离
*/
@Service
@log(logType = LogType.Slf4j)
class RedisService @Autowired() (redisTemplate: RedisTemplate[String, String]) {
private final lazy val LOGGER: Logger = LoggerFactory.getLogger(classOf[RedisService])
/** 获取Set集合数据
*
* @param k
......@@ -67,7 +66,7 @@ class RedisService @Autowired() (redisTemplate: RedisTemplate[String, String]) {
*/
def setTime(key: String, value: String, timeOut: Long, unit: TimeUnit): Unit = {
if (value == null) {
LOGGER.info("redis存储的value的值为空")
log.info("redis存储的value的值为空")
throw new IllegalArgumentException("redis存储的value的值为空")
}
if (timeOut > 0) redisTemplate.opsForValue().set(key, value, timeOut, unit)
......@@ -81,7 +80,7 @@ class RedisService @Autowired() (redisTemplate: RedisTemplate[String, String]) {
*/
def set(key: String, value: String): Unit = {
if (value == null) {
LOGGER.info("redis存储的value的值为空")
log.info("redis存储的value的值为空")
throw new IllegalArgumentException("redis存储的value的值为空")
}
redisTemplate.opsForValue().set(key, value)
......
package io.github.dreamylost.websocket
import akka.Done
import akka.NotUsed
import akka.actor.ActorRef
import akka.actor.ActorSystem
import akka.actor.Status
import akka.http.scaladsl.model.ws.Message
import akka.http.scaladsl.model.ws.TextMessage
import akka.stream.ActorMaterializer
import akka.stream.Materializer
import akka.stream.OverflowStrategy
import akka.stream.scaladsl.Flow
import akka.stream.scaladsl.Keep
import akka.stream.scaladsl.Sink
import akka.stream.scaladsl.Source
import akka.Done
import akka.NotUsed
import io.github.dreamylost.constant.SystemConstant
import akka.stream.ActorMaterializer
import akka.stream.Materializer
import io.github.dreamylost.log
import io.github.dreamylost.logs.LogType
import io.github.dreamylost.websocket.Protocols._
import io.github.dreamylost.websocket.SpringExtension.SpringExtProvider
import org.reactivestreams.Publisher
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.DependsOn
import org.springframework.stereotype.Component
......@@ -37,6 +37,7 @@ import scala.language.postfixOps
*/
@Component
@DependsOn(Array("redisService"))
@log(logType = LogType.Slf4j)
class WebSocketProvider @Autowired() (redisService: RedisService, wsService: WebSocketService)(
implicit system: ActorSystem
) {
......@@ -44,7 +45,6 @@ class WebSocketProvider @Autowired() (redisService: RedisService, wsService: Web
implicit val ec: ExecutionContextExecutor = system.dispatcher
implicit val mat: Materializer = ActorMaterializer()
private final lazy val log: Logger = LoggerFactory.getLogger(classOf[WebSocketProvider])
private final lazy val wsConnections = wsService.actorRefSessions
private lazy val msgActor =
system.actorOf(SpringExtProvider.get(system).props(ActorNames.MESSAGE_HANDLE_ACTOR))
......
......@@ -7,15 +7,15 @@ import akka.http.scaladsl.settings.ServerSettings
import akka.util.ByteString
import com.typesafe.config.ConfigFactory
import io.github.dreamylost.constant.SystemConstant
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import io.github.dreamylost.log
import io.github.dreamylost.logs.LogType
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.util.concurrent.atomic.AtomicInteger
import scala.concurrent.ExecutionContextExecutor
import scala.concurrent.Future
import scala.io.StdIn
import scala.concurrent.ExecutionContextExecutor
/** akka-http websocket server
*
......@@ -25,6 +25,7 @@ import scala.concurrent.ExecutionContextExecutor
* @version 1.0,2020/1/22
*/
@Component
@log(logType = LogType.Slf4j)
class WebSocketServer @Autowired() (redisService: RedisService, akkaService: WebSocketProvider)(
implicit system: ActorSystem
) {
......@@ -33,7 +34,6 @@ class WebSocketServer @Autowired() (redisService: RedisService, akkaService: Web
implicit val ec: ExecutionContextExecutor = system.dispatcher
private final lazy val LOGGER: Logger = LoggerFactory.getLogger(classOf[WebSocketServer])
private val host = ConfigFactory.load("application.conf").getString("akka-http-server.host")
private val port = ConfigFactory.load("application.conf").getInt("akka-http-server.port")
......@@ -51,7 +51,7 @@ class WebSocketServer @Autowired() (redisService: RedisService, akkaService: Web
path("websocket") {
get {
parameters("uid".as[Int]) { uid =>
LOGGER.info(s"新连接加入 => [userId = $uid]")
log.info(s"新连接加入 => [userId = $uid]")
redisService.setSet(SystemConstant.ONLINE_USER, uid + "")
// akkaService.userStatusChangeByServer(uid, "online")
handleWebSocketMessages(akkaService.openConnection(uid))
......@@ -63,9 +63,9 @@ class WebSocketServer @Autowired() (redisService: RedisService, akkaService: Web
def startUp(): Unit = {
val bindingFuture = Http().bindAndHandle(imRoute, host, port, settings = imServerSettings)
bindingFuture.failed.foreach { ex =>
LOGGER.error(s"Failed to bind to $host:$port!", ex)
log.error(s"Failed to bind to $host:$port!", ex)
}
LOGGER.info(
log.info(
"""
| __ __ ___. _________ __ __ _________
|/ \ / \ ____\_ |__ / _____/ ____ ____ | | __ _____/ |_ / _____/ ______________ __ ___________
......@@ -75,7 +75,7 @@ class WebSocketServer @Autowired() (redisService: RedisService, akkaService: Web
| \/ \/ \/ \/ \/ \/ \/ \/ \/ \/
|""".stripMargin
)
LOGGER.info(s"Websocket listening on [$host:$port]")
log.info(s"Websocket listening on [$host:$port]")
StdIn.readLine()
bindingFuture.flatMap(_.unbind()).onComplete(_ => system.terminate())
}
......
......@@ -4,6 +4,8 @@ import akka.actor.ActorRef
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.ScalaObjectMapper
import io.github.dreamylost.constant.SystemConstant
import io.github.dreamylost.log
import io.github.dreamylost.logs.LogType
import io.github.dreamylost.model.domains.Add
import io.github.dreamylost.model.domains.Receive
import io.github.dreamylost.model.entities.AddMessage
......@@ -12,8 +14,6 @@ import io.github.dreamylost.model.entities.User
import io.github.dreamylost.service.UserService
import io.github.dreamylost.util.DateUtil
import io.github.dreamylost.util.Jackson
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
......@@ -30,14 +30,15 @@ import scala.jdk.CollectionConverters._
* @version 1.2
*/
@Service
@log(logType = LogType.Slf4j)
class WebSocketService @Autowired() (
userService: UserService,
redisService: RedisService,
objectMapper: ObjectMapper with ScalaObjectMapper
) {
private final lazy val LOGGER: Logger = LoggerFactory.getLogger(classOf[WebSocketService])
final val actorRefSessions = new ConcurrentHashMap[Integer, ActorRef]
final lazy val actorRefSessions: ConcurrentHashMap[Integer, ActorRef] =
new ConcurrentHashMap[Integer, ActorRef]
/** 发送消息
*
......@@ -45,12 +46,12 @@ class WebSocketService @Autowired() (
*/
def sendMessage(message: Message): Unit =
message.synchronized {
LOGGER.debug(s"好友消息或群消息 => [msg = $message]")
log.debug(s"好友消息或群消息 => [msg = $message]")
//封装返回消息格式
val gid = message.to.id
val receive = getReceive(message)
//聊天类型,可能来自朋友或群组
if ("friend" == message.to.`type`) {
if (SystemConstant.FRIEND_TYPE == message.to.`type`) {
val msg = if (actorRefSessions.containsKey(gid)) {
val actorRef = actorRefSessions.get(gid)
val tmpReceiveArchive = receive.copy(status = 1)
......@@ -90,7 +91,7 @@ class WebSocketService @Autowired() (
* @param msg
*/
def agreeAddGroup(msg: Message): Unit = {
LOGGER.debug(s"同意入群消息 => [msg = $msg]")
log.debug(s"同意入群消息 => [msg = $msg]")
val agree = objectMapper.readValue[Protocols.AgreeAddGroup](msg.msg)
agree.messageBoxId.synchronized {
userService.addGroupMember(agree.groupId, agree.toUid, agree.messageBoxId)
......@@ -102,7 +103,7 @@ class WebSocketService @Autowired() (
* @param msg
*/
def refuseAddGroup(msg: Message): Unit = {
LOGGER.debug(s"拒绝入群消息 => [msg = $msg]")
log.debug(s"拒绝入群消息 => [msg = $msg]")
val refuse = objectMapper.readValue[Protocols.AgreeAddGroup](msg.msg)
refuse.messageBoxId.synchronized {
userService.updateAddMessage(refuse.messageBoxId, 2)
......@@ -116,11 +117,11 @@ class WebSocketService @Autowired() (
*/
def removeFriend(uId: Int, friendId: Int): Unit =
uId.synchronized {
LOGGER.debug(s"删除好友通知消息 => [uId = $uId, friendId = $friendId ]")
log.debug(s"删除好友通知消息 => [uId = $uId, friendId = $friendId ]")
//对方是否在线,在线则处理,不在线则不处理
val result = new util.HashMap[String, String]
if (actorRefSessions.get(friendId) != null) {
result.put("type", "delFriend")
result.put("type", Protocols.ImProtocol.delFriend.stringify)
result.put("uId", uId + "")
sendMessage(objectMapper.writeValueAsString(result), actorRefSessions.get(friendId))
}
......@@ -133,7 +134,7 @@ class WebSocketService @Autowired() (
*/
def addGroup(uId: Int, message: Message): Unit =
uId.synchronized {
LOGGER.debug(s"加群消息 => [uId = $uId, msg = $message ]")
log.debug(s"加群消息 => [uId = $uId, msg = $message ]")
val mine = message.mine
val to = message.to
val t = objectMapper.readValue[Protocols.Group](message.msg)
......@@ -149,7 +150,7 @@ class WebSocketService @Autowired() (
)
val result = new util.HashMap[String, String]
if (actorRefSessions.get(to.id) != null) {
result.put("type", "addGroup")
result.put("type", Protocols.ImProtocol.addGroup.stringify)
sendMessage(objectMapper.writeValueAsString(result), actorRefSessions.get(to.id))
}
}
......@@ -161,7 +162,7 @@ class WebSocketService @Autowired() (
*/
def addFriend(uId: Int, message: Message): Unit =
uId.synchronized {
LOGGER.debug(s"加好友消息 => [uId = $uId, msg = $message ]")
log.debug(s"加好友消息 => [uId = $uId, msg = $message ]")
val mine = message.mine
val add = objectMapper.readValue[Add](message.msg)
val addMessageCopy = AddMessage(
......@@ -176,7 +177,7 @@ class WebSocketService @Autowired() (
val result = new util.HashMap[String, String]
//如果对方在线,则推送给对方
if (actorRefSessions.get(message.to.id) != null) {
result.put("type", "addFriend")
result.put("type", Protocols.ImProtocol.addFriend.stringify)
sendMessage(
objectMapper.writeValueAsString(result),
actorRef = actorRefSessions.get(message.to.id)
......@@ -191,11 +192,11 @@ class WebSocketService @Autowired() (
*/
def countUnHandMessage(uId: Int): util.HashMap[String, String] =
uId.synchronized {
LOGGER.debug(s"离线消息统计 => [uId = $uId]")
log.debug(s"离线消息统计 => [uId = $uId]")
val count = userService.countUnHandMessage(uId, 0)
LOGGER.info("count = " + count)
log.info("count = " + count)
val result = new util.HashMap[String, String]
result.put("type", "unHandMessage")
result.put("type", Protocols.ImProtocol.unHandMessage.stringify)
result.put("count", count + "")
result
}
......@@ -207,12 +208,13 @@ class WebSocketService @Autowired() (
*/
def checkOnline(message: Message): util.HashMap[String, String] =
message.to.id.synchronized {
LOGGER.debug(s"检测在线状态 => [msg = ${message.to.toString}]")
log.debug(s"检测在线状态 => [msg = ${message.to.toString}]")
val uids = redisService.getSets(SystemConstant.ONLINE_USER)
val result = new util.HashMap[String, String]
result.put("type", "checkOnline")
if (uids.contains(message.to.id.toString)) result.put("status", "在线")
else result.put("status", "离线")
result.put("type", Protocols.ImProtocol.checkOnline.stringify)
if (uids.contains(message.to.id.toString))
result.put("status", SystemConstant.status.ONLINE_DESC)
else result.put("status", SystemConstant.status.HIDE_DESC)
result
}
......@@ -256,26 +258,31 @@ class WebSocketService @Autowired() (
*/
def changeOnline(uId: Int, status: String): Boolean =
uId.synchronized {
val isOnline = "online".equals(status)
LOGGER.debug(s"检测在线状态 => [uId = $uId, status = $status]")
val isOnline = SystemConstant.status.ONLINE.equals(status)
log.debug(s"检测在线状态 => [uId = $uId, status = $status]")
if (isOnline) redisService.setSet(SystemConstant.ONLINE_USER, uId + "")
else redisService.removeSetValue(SystemConstant.ONLINE_USER, uId + "")
// 向我的所有在线好友发送广播消息,告知我的状态变更,否则只能再次打聊天开窗口时变更,todo 异步发送
userService
.findFriendGroupsById(uId)
.asScala
.foreach(fl => {
.filter(l => l != null && l.list != null && !l.list.isEmpty)
.foreach { fl =>
fl.list.asScala.foreach(u => {
val fu = redisService.getSets(SystemConstant.ONLINE_USER).contains(u.id.toString)
val actorRef = actorRefSessions.get(u.id)
if (fu && actorRef != null) {
val msg = Jackson.mapper.writeValueAsString(
Map("type" -> "checkOnline", "status" -> (if (isOnline) "在线" else "离线"))
Map(
"type" -> Protocols.ImProtocol.checkOnline.stringify,
"status" -> (if (isOnline) SystemConstant.status.ONLINE_DESC
else SystemConstant.status.HIDE_DESC)
)
)
sendMessage(msg, actorRef)
}
})
})
}
userService.updateUserStatus(User(uId, status))
}
......@@ -285,7 +292,7 @@ class WebSocketService @Autowired() (
*/
def readOfflineMessage(message: Message): Unit = {
message.mine.id.synchronized {
if (message.to.`type` == "group") {
if (message.to.`type` == SystemConstant.GROUP_TYPE) {
userService.readGroupMessage(message.mine.id, message.mine.id)
} else {
userService.readFriendMessage(message.mine.id, message.to.id)
......
<%@page contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>该页面不存在-404.life</title>
<link rel="shortcut icon" href="/static/image/favicon.ico">
<link rel="stylesheet" href="/static/css/style.css">
</head>
<body>
<!-- partial:index.partial.html -->
<div class="container">
<div class="display">
<h1 class="num"></h1>
<h1 class="stg"></h1>
</div>
<a href="/user/index" title="">返回主页</a>
</div>
<!-- partial -->
<script src="/static/js/script.js"></script>
</body>
</html>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
color: #F1F1F1;
}
body{
font-family: Verdana, Geneva, Tahoma, sans-serif;
background: rgb(238,174,202);
background: radial-gradient(circle, rgba(238,174,202,1) 0%, rgba(148,187,233,1) 100%);
}
.container{
height : 100vh;
width: 80vw;
margin: 0 auto;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
text-align: center;
}
.container .num {
font-size: 8rem;
margin-bottom: 40px;
}
.container .stg {
font-size: 3rem;
margin-bottom: 40px;
display: none;
animation: .7s ease-in-out show;
}
@keyframes show {
0%{
opacity : 0;
}100%{
opacity: 1;
}
}
\ No newline at end of file
// Declare the Elements
const dispNum = document.querySelector(".display .num");
const dispErr = document.querySelector(".container .stg");
window.onload = function () {
function showNum () {
const randomNum = Math.floor(Math.random() * 1000);
const randomStr = randomNum.toString()
dispNum.textContent = randomStr
}
var interval = setInterval( showNum , 500);
setTimeout(()=> {
clearInterval(interval);
dispNum.textContent = "404";
dispErr.style.display = "block";
dispErr.textContent = "呀!这个页面走丢了"
}, 4000);
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册