话不多说,直接上代码,语法什么的就不说了
maven中加入依赖包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>1.5.9.RELEASE</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.6</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.31</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> <version>1.5.9.RELEASE</version> </dependency>
整体目录结构
配置文件
spring.application.name=springboot_kotlin server.port=8080 #datasource spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.url=jdbc:mysql://localhost:3306/kotlin?characterEncoding=utf8&useSSL=true spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver #连接池的配置信息 spring.datasource.initialSize=5 spring.datasource.minIdle=5 spring.datasource.maxActive=20 spring.datasource.maxWait=60000 spring.datasource.timeBetweenEvictionRunsMillis=60000 spring.datasource.minEvictableIdleTimeMillis=300000 spring.datasource.validationQuery=SELECT 1 FROM DUAL spring.datasource.testWhileIdle=true spring.datasource.testOnBorrow=false spring.datasource.testOnReturn=false spring.datasource.poolPreparedStatements=true spring.datasource.maxPoolPreparedStatementPerConnectionSize=20 spring.datasource.filters=stat,wall,log4j spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 #jpa spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=update spring.jpa.open-in-view=true #Thymeleaf spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.cache=false #redis spring.redis.port=6379 spring.redis.host=localhost spring.redis.database=0 spring.redis.password= spring.redis.pool.max-active=8 spring.redis.pool.max-wait=-1 spring.redis.pool.max-idle=8 spring.redis.pool.min-idle=0 spring.redis.timeout=0 #rabbitmq spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=xh spring.rabbitmq.password=123456 spring.rabbitmq.virtual-host=/
主类:KotlinDemoApplication一般来说只要加入注解@SpringBootApplication就好,@ServletComponentScan是为了集成Druid的时候可以扫描到DruidServlet
@SpringBootApplication @ServletComponentScan class KotlinDemoApplication fun main(args: Array<String>) { SpringApplication.run(KotlinDemoApplication::class.java, *args) }
新建个User对象
@Entity @Table(name = "t_user") data class User( @Id @GeneratedValue(strategy = GenerationType.AUTO) var id: Int = 0, var name: String = "" ):Serializable
UserRepository
interface UserRepository : CrudRepository<User, Int> { @Query("select user from User as user where user.name=:name") fun getUserList(@Param("name") name: String): MutableList<User> }
UserDao
interface UserDao { fun addUser(user: User): User fun getUserById(id: Int): User fun getListByName(name: String): MutableList<User> }
UserService
@Service class UserService : UserDao { @Autowired lateinit var userRepository: UserRepository @Autowired lateinit var sendService: SendService @PersistenceContext private val em: EntityManager? = null fun getEm() = em!! /** * jpql方式等同于 * @query("select u from User u where u.name = :name order by u.id desc") * fun getUserListByName(): MutableList<Any?>? */ fun getUserListByName(name: String): MutableList<User> { var sql = "select u from User u where u.name = :name order by u.id desc" val query = getEm().createQuery(sql) query.setParameter("name", name) return query?.resultList as MutableList<User> } /** * 源生sql方式 */ fun getAlluserListByName(name: String): MutableList<User> { var sql = "select id,name from t_user as u where u.name = ? order by u.id desc limit 10" var query = getEm().createNativeQuery(sql).setParameter(1, name) query.unwrap(SQLQuery::class.java).setResultTransformer(Transformers.aliasToBean(User::class.java)) return query.resultList as MutableList<User> } override fun addUser(user: User) = userRepository.save(user) override fun getUserById(id: Int) = userRepository.findOne(id) override fun getListByName(name: String): MutableList<User> = userRepository.getUserList(name) fun sendMsg(msg: String) { sendService.sendMsg(msg) } }
redis配置文件
@Configuration @EnableCaching class RedisConfig : CachingConfigurerSupport() { @Bean override fun keyGenerator(): KeyGenerator { return KeyGenerator { target, method, params -> val sb = StringBuilder() sb.append(target.javaClass.name) sb.append(method.name) for (obj in params) { sb.append(obj.toString()) } sb.toString() } } @Bean fun cacheManager( redisTemplate: RedisTemplate<*, *>): CacheManager { return RedisCacheManager(redisTemplate) } @Bean fun redisTemplate( factory: RedisConnectionFactory): RedisTemplate<String, String> { val template = StringRedisTemplate(factory) val jackson2JsonRedisSerializer = Jackson2JsonRedisSerializer(Any::class.java) val om = ObjectMapper() om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY) om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL) jackson2JsonRedisSerializer.setObjectMapper(om) template.valueSerializer = jackson2JsonRedisSerializer template.afterPropertiesSet() return template } }
DruidConfig
@Configuration class DruidConfig { @Value("\${spring.datasource.url}") val dbUrl: String? = null @Value("\${spring.datasource.username}") val username: String? = null @Value("\${spring.datasource.password}") val password: String? = null @Value("\${spring.datasource.driver-class-name}") val driverClassName: String? = null @Value("\${spring.datasource.initialSize}") val initialSize: Int = 0 @Value("\${spring.datasource.minIdle}") val minIdle: Int = 0 @Value("\${spring.datasource.maxActive}") val maxActive: Int = 0 @Value("\${spring.datasource.maxWait}") val maxWait: Int = 0 @Value("\${spring.datasource.timeBetweenEvictionRunsMillis}") val timeBetweenEvictionRunsMillis: Int = 0 @Value("\${spring.datasource.minEvictableIdleTimeMillis}") val minEvictableIdleTimeMillis: Int = 0 @Value("\${spring.datasource.validationQuery}") val validationQuery: String? = null @Value("\${spring.datasource.testWhileIdle}") val testWhileIdle: Boolean = false @Value("\${spring.datasource.testOnBorrow}") val testOnBorrow: Boolean = false @Value("\${spring.datasource.testOnReturn}") val testOnReturn: Boolean = false @Value("\${spring.datasource.poolPreparedStatements}") val poolPreparedStatements: Boolean = false @Value("\${spring.datasource.maxPoolPreparedStatementPerConnectionSize}") val maxPoolPreparedStatementPerConnectionSize: Int = 0 @Value("\${spring.datasource.filters}") val filters: String? = null @Value("\${spring.datasource.connectionProperties}") val connectionProperties: String? = null @Bean //声明其为Bean实例 @Primary //在同样的DataSource中,首先使用被标注的DataSource fun dataSource(): DataSource { val datasource = DruidDataSource() datasource.url = this.dbUrl datasource.username = username datasource.password = password datasource.driverClassName = driverClassName //configuration datasource.initialSize = initialSize datasource.minIdle = minIdle datasource.maxActive = maxActive datasource.maxWait = maxWait.toLong() datasource.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis.toLong() datasource.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis.toLong() datasource.validationQuery = validationQuery datasource.isTestWhileIdle = testWhileIdle datasource.isTestOnBorrow = testOnBorrow datasource.isTestOnReturn = testOnReturn datasource.isPoolPreparedStatements = poolPreparedStatements datasource.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize try { datasource.setFilters(filters) } catch (e: SQLException) { e.printStackTrace() } datasource.setConnectionProperties(connectionProperties) return datasource } }
DruidFilter
@WebFilter(filterName = "druidWebStatFilter", urlPatterns = ["/*"], initParams = [(WebInitParam(name = "exclusions", value = "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"))]) class DruidFilter : WebStatFilter()
DruidServlet
/** * allow 白名单 * deny 黑名单(优先级高于白名单,同时存在时deny高于allow) * loginUsername 访问页面登录名 * loginPassword 访问页面登录密码 * resetEnable 是否重置数据 */ @WebServlet(urlPatterns = ["/druid/*"], initParams = [(WebInitParam(name = "allow", value = "")), (WebInitParam(name = "deny", value = "192.168.0.121")), (WebInitParam(name = "loginUsername", value = "admin")), (WebInitParam(name = "loginPassword", value = "123456")), (WebInitParam(name = "resetEnable", value = "false"))])//禁止页面reset all class DruidServlet : StatViewServlet()
RabbitMqConfig
@Configuration @EnableRabbit class RabbitMqConfig { @Bean fun queue() = Queue("myqueue", true) @Bean fun topExchange() = TopicExchange("myexchange") @Bean fun binding() = BindingBuilder.bind(queue()).to(topExchange()).with("myqueue") }
SendService
@Component class SendService(val rabbitTemplate: RabbitTemplate) { fun sendMsg(jsonstring: String) { println("开始发消息---------------------") val correlationData = CorrelationData(UUID.randomUUID().toString()) rabbitTemplate.convertAndSend("myexchange", "myqueue", jsonstring, correlationData) } }
ReceiveService
@Component class ReceiveService { @RabbitHandler @RabbitListener(queues = ["myqueue"]) fun getMessage(message: String) { println("收到的消息:--$message") } }
UserController
@RestController class UserController { @Autowired lateinit var userService: UserService @Autowired lateinit var redisTemplate: RedisTemplate<String, String> @GetMapping("/") fun get(): String = redisTemplate.opsForValue().get("sher") @GetMapping("add") fun addUser(): User? { var user = User(name = "sher") return userService.addUser(user) } @GetMapping("findone/{id}") fun findAllUser(@PathVariable id: Int, model: Model) = userService.getUserById(id) @GetMapping("find/{name}") fun findByName(@PathVariable name: String) = userService.getListByName(name) @GetMapping("get/{name}") fun getName(@PathVariable name: String) = userService.getUserListByName(name) @GetMapping("get1/{name}") fun getList(@PathVariable name: String) = userService.getAlluserListByName(name) @GetMapping("send/{msg}") fun sendMsg(@PathVariable msg:String)=userService.sendMsg(msg) }
上面就是所以文件几乎和java没什么区别,如果不想写kotlin的直接调用java的就可以。
把demo放github上了地址:传送门biubiubiu